Suppose I have the dict of a module (via vars(mod)
, or mod.__dict__
, or globals()
), e.g.:
import mod
d = vars(mod)
Given the dict d
, how can I get back the module mod
? I.e. I want to write a function get_mod_from_dict(d)
, which returns the module if the dict belongs to a module, or None
:
>>> get_mod_from_dict(d)
<module 'mod'>
If get_mod_from_dict
returns a module, I must have that this holds:
mod = get_mod_from_dict(d)
assert mod is None or mod.__dict__ is d
I actually can implement it like this:
def get_mod_from_dict(d):
mods = {id(mod.__dict__): mod for (modname, mod) in sys.modules.items()
if mod and modname != "__main__"}
return mods.get(id(d), None)
However, this seems inefficient to me, to iterate through sys.modules
.
Is there a better way?
Why do I need this?
In some cases, you get access to the dict only. E.g. in the stack frames. And then, depending on what you want to do, maybe just for inspection/debugging purpose, it is helpful to get back the module.
I wrote some extension to
Pickler
which can pickle methods, functions, etc. Some of these have references to the module, or the module dict. Wherever I have a dict which belongs to a module during pickling, I don't want to pickle the dict, but instead a reference to the module.