Get module instance given its vars dict
Every module has a __name__
attribute that uniquely identifies the module in the import system:
>>> import os
>>> os.__name__
'os'
>>> vars(os)['__name__']
'os'
Imported modules are also cached in sys.modules
, which is a dict mapping module names to module instances. You can simply look up the module's name there:
import sys
def get_mod_from_dict(module_dict):
module_name = module_dict['__name__']
return sys.modules.get(module_name)
Some people have expressed concern that this might not work for (sub-)modules in packages, but it does:
>>> import urllib.request
>>> get_mod_from_dict(vars(urllib.request))
<module 'urllib.request' from '/usr/lib/python3.7/urllib/request.py'>
There is a very minor caveat, though: This will only work for modules that have been properly imported and cached by the import machinery. If a module has been imported with tricks like How to import a module given the full path?, it might not be cached in sys.modules
and your function might then unexpectedly return None
.
You can use importlib.import_module to import a module given it's name. Example for numpy
In [77]: import numpy
...: import importlib
In [78]: d = vars(numpy)
In [79]: np = importlib.import_module(d['__name__'])
In [80]: np.array([1,2,3])
Out[80]: array([1, 2, 3])