File tree Expand file tree Collapse file tree 5 files changed +56
-0
lines changed Expand file tree Collapse file tree 5 files changed +56
-0
lines changed Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff line change 1+ metadata (version = "0.1.0" )
2+
3+ module ("importlib.py" )
Original file line number Diff line number Diff line change 1+ test_data = "one"
Original file line number Diff line number Diff line change 1+ test_data = "two"
Original file line number Diff line number Diff line change 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"
You can’t perform that action at this time.
0 commit comments