1

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.

asked Mar 15, 2018 at 11:49

1 Answer 1

1

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
answered Mar 15, 2018 at 12:30
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.