Python Forum

Full Version: How to use a module as dict ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
is it possible to add dictionary property to module.  we can add dictionary property to classes with adding __getitem__ method. i hope we can do that same thing on modules.

example

import mymodule

print( mymodule["2 + 2"]  )

# output =>  '4'

I tried it but it not working

#mymodule.py

__dict__ = {"2 + 2": "4",  "python": 3.4, "os": "fedora"}

def __getitem__(key):
    return __dict__[key]
So far as I'm aware, this isn't possible. Why do you want to do it? We might be able to suggest a different way of achieving your goal.
Why not just have a thing in the module that does that, instead of having the module itself do it?
If want to import can do it like this,remember a module is just a single Python file.
>>> from bar import mymodule
>>> mymodule('2 + 2')
'4'
>>> mymodule('os')
'fedora'
>>> mymodule('java')
'Not in record'
# bar.py
def mymodule(arg):
    return {
        "2 + 2": "4",
        "python": 3.4,
        "os": "fedora"
        }.get(arg, 'Not in record')
thanks for answer. i want only good code view but python sometimes can be very annoying. okay. at least i learned that is not possible.