![]() |
How to use a module as dict ? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to use a module as dict ? (/thread-3326.html) |
How to use a module as dict ? - harun2525 - May-15-2017 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] RE: How to use a module as dict ? - micseydel - May-15-2017 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. RE: How to use a module as dict ? - nilamo - May-15-2017 Why not just have a thing in the module that does that, instead of having the module itself do it? RE: How to use a module as dict ? - snippsat - May-15-2017 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') RE: How to use a module as dict ? - harun2525 - May-15-2017 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. |