Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Andrew Svk
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.
Here is an example of how the error occurs. Imagine we have 2 files -
another.py
and main.py
.
my_dict = {'name': 'Alice', 'age': 30}
And here is the content for 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.
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.
from another import my_dict print(my_dict['name']) # 👉️ "Alice"
This import statement only imports the my_dict
variable from the another.py
module.
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.
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.
import another print(another.my_dict) # 👉️ {'name': 'Alice', 'age': 30}
Alternatively, you can import the my_dict
variable directly.
from another import my_dict print(my_dict) # 👉️ {'name': 'Alice', 'age': 30}
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).