Skip to content

Commit 34f8abd

Browse files
committed
importlib: Add reimplemented basic importlib module.
Signed-off-by: Andrew Leech <andrew@alelec.net>
1 parent e4cf095 commit 34f8abd

File tree

5 files changed

+56
-0
lines changed

5 files changed

+56
-0
lines changed

python-stdlib/importlib/importlib.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
Provide subset of CPython api-compatible importlib module.
3+
"""
4+
import sys
5+
6+
7+
def import_module(name, package=None):
8+
# https://docs.python.org/3/library/importlib.html#importlib.import_module
9+
if package:
10+
raise NotImplementedError()
11+
mods = name.split(".")
12+
mod = __import__(name)
13+
while len(mods) > 1:
14+
mod = getattr(mod, mods.pop(1))
15+
return mod
16+
17+
18+
def reload(module):
19+
"""
20+
https://docs.python.org/3/library/importlib.html#importlib.reload
21+
"""
22+
fullname = module.__name__
23+
if sys.modules.get(fullname) is not module:
24+
raise ImportError("module %s not in sys.modules" % fullname)
25+
sys.modules.pop(fullname)
26+
newmod = import_module(fullname)
27+
try:
28+
# Update parent frame object
29+
pfglobals = sys._getframe(1).f_globals
30+
for name, obj in list(pfglobals.items()):
31+
if obj is module:
32+
pfglobals[name] = newmod
33+
except AttributeError:
34+
# Can't update parent frame without sys._getframe
35+
pass
36+
return newmod

python-stdlib/importlib/manifest.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
metadata(version="0.1.0")
2+
3+
module("importlib.py")
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
test_data = "one"
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
test_data = "two"
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import sys
2+
sys.path.append(".")
3+
import importlib
4+
5+
sys.path.append("tests/imp1")
6+
import importlib_test_data
7+
assert importlib_test_data.test_data == "one"
8+
9+
sys.path.remove("tests/imp1")
10+
sys.path.append("tests/imp2")
11+
12+
nm = importlib.reload(importlib_test_data)
13+
import importlib_test_data
14+
15+
assert importlib_test_data.test_data == "two"

0 commit comments

Comments
 (0)