TypeError: 'module' object is not subscriptable in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Andrew Svk

TypeError: 'module' object is not subscriptable in Python #

The Python "TypeError: 'module' object is not subscriptable" occurs when we import a module as import some_module but use square brackets to access a specific key. To solve the error, use dot notation to access the specific variable or import it directly.

typeerror module object is not subscriptable

Here is an example of how the error occurs. Imagine we have 2 files - another.py and main.py.

another.py
my_dict = {'name': 'Alice', 'age': 30}

And here is the content for main.py.

main.py
import another # ⛔️ TypeError: 'module' object is not subscriptable print(another['name'])

The issue is that, in the main.py file, we import the another module but use square brackets to try to access a key in the my_dict variable.

One way to solve the error is to use dot notation to access the variable before we try to access a key (or index if using lists).
main.py
import another print(another.my_dict['name']) # 👉️ "Alice"

We used dot notation to get access to the dict object from another.py before trying to access a specific key.

Alternatively, you can import the my_dict variable from the another.py module.

main.py
from another import my_dict print(my_dict['name']) # 👉️ "Alice"

This import statement only imports the my_dict variable from the another.py module.

If you need to import multiple variables or functions, separate them by commas in the import statement, e.g. from another import first, second, third.

A good way to start debugging is to print(dir(your_module)) and see what attributes the imported module has.

Here is what printing the attributes of the another.py module looks like.

main.py
import another # 👉️ ['__builtins__', '__cached__', '__doc__', # '__file__', '__loader__', '__name__', '__package__', # '__spec__', 'my_dict'] 👈️ notice 'my_dict' print(dir(another))

If you pass a module object to the dir() function, it returns a list of names of the module's attributes.

Notice the my_dict attribute at the end of the list.

This means that we have to access the attribute as another.my_dict to get a reference to the dictionary.

main.py
import another print(another.my_dict) # 👉️ {'name': 'Alice', 'age': 30}

Alternatively, you can import the my_dict variable directly.

main.py
from another import my_dict print(my_dict) # 👉️ {'name': 'Alice', 'age': 30}
The "TypeError: object is not subscriptable" means that we are using square brackets to either access a key in a specific object or to access a specific index, however the object doesn't support this functionality.

Module objects are not subscriptable, so we have to access an attribute of the module to get a hold of a dict or a list object (which are subscriptable).

Use the search field on my Home Page to filter through my more than 1,000 articles.