Skip to content

Commit 6655741

Browse files
Prefer using the module loader to get source in builder. (#1207)
* Use loader.get_source() in builder.module_build() Otherwise we fail to get the module source code when running in an embedded hermetic interpreter environment where the source does not live on a filesystem. Co-authored-by: Pierre Sassoulas <[email protected]>
1 parent 8ce5987 commit 6655741

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

ChangeLog

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,12 @@ What's New in astroid 2.9.1?
1212
============================
1313
Release date: TBA
1414

15+
* Prefer the module loader get_source() method in AstroidBuilder's
16+
module_build() when possible to avoid assumptions about source
17+
code being available on a filesystem. Otherwise the source cannot
18+
be found and application behavior changes when running within an
19+
embedded hermetic interpreter environment (pyoxidizer, etc.).
20+
1521
* Require Python 3.6.2 to use astroid.
1622

1723
* Fix ``deque.insert()`` signature in ``collections`` brain.

astroid/builder.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,15 @@ def module_build(
8787
"""Build an astroid from a living module instance."""
8888
node = None
8989
path = getattr(module, "__file__", None)
90-
if path is not None:
90+
loader = getattr(module, "__loader__", None)
91+
# Prefer the loader to get the source rather than assuming we have a
92+
# filesystem to read the source file from ourselves.
93+
if loader:
94+
modname = modname or module.__name__
95+
source = loader.get_source(modname)
96+
if source:
97+
node = self.string_build(source, modname, path=path)
98+
if node is None and path is not None:
9199
path_, ext = os.path.splitext(modutils._path_from_filename(path))
92100
if ext in {".py", ".pyc", ".pyo"} and os.path.exists(path_ + ".py"):
93101
node = self.file_build(path_ + ".py", modname)

0 commit comments

Comments
 (0)