So it's quite a simple question. how do I add __getitem__
to a Python module. I mostly just want it as an ease of use, however it's confusing why it wouldn't let me 'just set it'. Below is a simple example of __getitem__
semi-working, however I wish for the other['test']
to work.
Here's the full output:
hello
hello
Traceback (most recent call last):
File "main.py", line 4, in <module>
print other['test']
TypeError: 'module' object has no attribute '__getitem__'
main.py
import other
print other.get('test')
print other.__getitem__('test')
print other['test']
other.py
test = 'hello'
def __getitem__(name):
return globals()[name]
get = __getitem__
I've tried to set __getitem__
using globals()
aswell, globals()['__getitem__'] = __getitem__
. It didn't work. And I tried to set it in main.py
. So I'm confused as to why it's so adamant in not allowing me to use other['test']
.
If it's impossible, then a short reason would be good.