Reputation: 2188
I would like to make an imported module behave like an object, ie. an dictionary.
E.g.
import module
print(module['key'])
and in module.py
return {'key':'access'}
This is very easy for Class
by inheriting from dict
, but how do I do this on a module level?
In particular I want to dynamically built the dictionary in module
and return it when module
is imported.
I know that there are other solutions such as defining the dict
as a var
in the module
workspace and accessing it via module.var
, but I am interested if something like this is possible.
Upvotes: 1
Views: 543
Reputation: 11070
As you point out, you can do this with a class, but not with a module, as modules are not subscriptable.Now I'm not going to ask why you want to do this with an import
, but it can be done.
What you do is create a class that does what you want, and then have the module replace itself with the class when imported. This is of course a 'bit of a hack' (tm). Here I'm using UserDict as it gives easy access to the dict via the class attr data
, but you could do anything you like in this class:
# module.py
from collections import UserDict
import sys
import types
class ModuleDict(types.ModuleType, UserDict):
data = {'key': 'access}
sys.modules[__name__] = ModuleDict(__name__)
Then you can import the module and use it as desired:
# code.py
import module
print(module['key']
# access
Upvotes: 1