@@ -67,6 +67,9 @@ def __init__(
6767 self .new_modules : Dict [str , types .ModuleType ] = {
6868 "sys" : sys ,
6969 "builtins" : builtins ,
70+ # Even though we don't want to, we have to have __main__ because
71+ # stdlib packages like inspect and others expect it to be present
72+ "__main__" : types .ModuleType ("__main__" ),
7073 }
7174 self .modules_checked_for_restrictions : Set [str ] = set ()
7275 self .import_func = self ._import if not LOG_TRACE else self ._traced_import
@@ -334,7 +337,7 @@ def unapplied(self) -> Iterator[None]:
334337
335338
336339class _ThreadLocalSysModules (
337- _ThreadLocalOverride [MutableMapping [str , types .ModuleType ]],
340+ _ThreadLocalOverride [Dict [str , types .ModuleType ]],
338341 MutableMapping [str , types .ModuleType ],
339342):
340343 def __contains__ (self , key : object ) -> bool :
@@ -355,6 +358,35 @@ def __iter__(self) -> Iterator[str]:
355358 def __setitem__ (self , key : str , value : types .ModuleType ) -> None :
356359 self .current [key ] = value
357360
361+ # Below methods are not in mutable mapping. Python chose not to put
362+ # everything in MutableMapping they do in dict (see
363+ # https://bugs.python.org/issue22101). So when someone calls
364+ # sys.modules.copy() it breaks (which is exactly what the inspect module
365+ # does sometimes).
366+
367+ def __or__ (
368+ self , other : Mapping [str , types .ModuleType ]
369+ ) -> Dict [str , types .ModuleType ]:
370+ if sys .version_info < (3 , 9 ):
371+ raise NotImplementedError
372+ return self .current .__or__ (other )
373+
374+ def __ior__ (
375+ self , other : Mapping [str , types .ModuleType ]
376+ ) -> Dict [str , types .ModuleType ]:
377+ if sys .version_info < (3 , 9 ):
378+ raise NotImplementedError
379+ return self .current .__ior__ (other )
380+
381+ __ror__ = __or__
382+
383+ def copy (self ) -> Dict [str , types .ModuleType ]:
384+ return self .current .copy ()
385+
386+ @classmethod
387+ def fromkeys (cls , * args , ** kwargs ) -> Any :
388+ return dict .fromkeys (* args , ** kwargs )
389+
358390
359391_thread_local_sys_modules = _ThreadLocalSysModules (sys .modules )
360392
0 commit comments