Python Forum
How to use a module as dict ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to use a module as dict ?
#1
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]
Reply
#2
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.
Reply
#3
Why not just have a thing in the module that does that, instead of having the module itself do it?
Reply
#4
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')
Reply
#5
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sort a dict in dict cherry_cherry 4 101,278 Apr-08-2020, 12:25 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020