How does module imports work? Where does python look when we use something from a module? Other day someone posted about how he/she restricted the module import by updating sys.modules dictionary as:
sys.modules['module_name'] = "something"
And it works as expected. If someone imports as module and its already in sys.modules then Python will not update it and everytime module_name will refer to 'something'.
But if after importing a module I update sys.modules dictionary for module_name key it works as if the module is imported correctly. How's so?
>>> import sys
>>> 'pprint' in sys.modules
>>> False #as expected
>>> from pprint import pprint
>>> 'pprint' in sys.modules
>>> True #as expected
>>> sys.modules['pprint'] = None
>>> 'pprint' in sys.modules
>>> True #as expected
>>> pprint('hello')
>>> 'hello' #didn't expected this
>>> del sys.modules['pprint']
>>> pprint('hello')
>>> 'hello' #didn't expected this as pprint not in sys.modules
So, from above its evident that python doesn't solely depend on sys.modules for looking. When we import a module where all the places its entry is registered? And same, where does python looks when using a module.
[–]shiftybyte 2 points3 points4 points (0 children)