Typeerror: 'Module' Object Is Not Subscriptable

I'm using python version 3.6.

mystuff.py includes:

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

mystuffTest.py includes this

import mystuff
print (mystuff['donut'])

The error that I receive when I run mystuffTest.py is 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?

2 Answers

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'])
5

I got this error because a later from __ import * statement imported a module which bound my variable to something else:

from stuff_a import d
from stuff_b import *
d['key']

In stuff_b.py, d was bound to a module, hence the error. Lesson learned: avoid importing * from modules.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest