@@ -44,9 +44,30 @@ def _wrap(new, old):
4444 setattr (new , replace , getattr (old , replace ))
4545 new .__dict__ .update (old .__dict__ )
4646
47+ def _module_type ():
48+ sys_type = type (sys )
49+ if sys_type .__name__ == "module" :
50+ return sys_type
51+
52+ # The `sys` module is immutable, we need to get the module type
53+ # another way...
54+ mods = [_bootstrap_external , _thread , _warnings , _weakref ]
55+ for m in mods :
56+ if type (m ).__name__ == "module" :
57+ return type (m )
58+
59+ for m in sys .mut_modules .values ():
60+ if type (m ).__name__ == "module" :
61+ return type (m )
62+
63+ # There are other ways to make this work, we can for example
64+ # pass in the module type into a global variable in this script
65+ # or store the module in a global. This is a bridge we can cross,
66+ # when we get there.
67+ raise Exception ("sys and all other modules currently accessible are immutable, this is bad" )
4768
4869def _new_module (name ):
49- return type ( sys )(name )
70+ return _module_type ( )(name )
5071
5172
5273# Module-level locking ########################################################
@@ -1527,7 +1548,7 @@ def _setup(sys_module, _imp_module):
15271548 sys = sys_module
15281549
15291550 # Set up the spec for existing builtin/frozen modules.
1530- module_type = type ( sys )
1551+ module_type = _module_type ( )
15311552 for name , module in sys .modules .items ():
15321553 if isinstance (module , module_type ):
15331554 if name in sys .builtin_module_names :
0 commit comments