TypeError: 'module' object is not subscrip

2020-08-26 11:01发布

问题:

mystuff.py includes a module. I'm using python version 3.6.

mystuff = {'donut': "SHE LOVES DONUTS!"}

mystuffTest.py includes this

import mystuff

print (mystuff['donut'])

The error that I receive when I run mystuffTest.py as follows:

$ python3.6 mystuffTrythis.py 
Traceback (most recent call last):
  File "mystuffTrythis.py", line 3, in <module>
    print (mystuff['donut'])
TypeError: 'module' object is not subscriptable

So far I haven't seen this exact error here on stackoverflow. Can anyone explain why I am getting this error?

回答1:

import mystuff is importing the module mystuff, not the variable mystuff. To access the variable you'd need to use:

import mystuff
print(mystuff.mystuff['donut'])

EDIT: It's also possible to import the variable directly, using:

from mystuff import mystuff
print(mystuff['donut'])


标签: python