Limited scope importer

I’m working on an import loader and finder that would allow me to specify an “external” path/environment to read from. I’ve gotten it working somewhat but I would like to have the imported modules known only inside this context/scope. I was hoping to achieve this by swapping sys.module when entering the context. Now this works fine, until I reach a point where a compiled module, e.g. _decimal is loading. Then the system doesn’t seem to be using the new sys.module object that is used in the python implementation.

Could anyone point me at the part of the source code where these imports happen or provide any further explanation of how the cpython imports differ from .py module imports?

The line you’re looking for is

The difference is that there is a field on the C struct representing the interpreter which has the canonical dict for where modules are cached. sys.modules gets set to this dict, but all C code reads from the struct and not what’s in sys.modules for performance reasons.

Basically you can’t swap out sys.modules and instead should always mutate it in place.

1 Like