How to Solve Python TypeError: ‘module’ object is not subscriptable

by | Programming, Python, Tips

This error occurs when you try to use indexing syntax to access values in a module.

A Python module is a file containing Python code. A module can define functions, classes, and variables. You can import modules into your program.

You can solve this error by using dot notation to access the subscriptable variable from the module or import the variable directly.

This tutorial will go through how to solve the error with code examples.


TypeError: ‘module’ object is not subscriptable

Let’s break up the error message to understand what the error means. TypeError occurs whenever you attempt to use an illegal operation for a specific data type. The part “module object” tells us the error concerns an illegal operation for Python modules.

The part “is not subscriptable” tells us we cannot access an element of the module object using the subscript operator, which is square brackets [].

A subscriptable object is a container for other objects and implements the __getitem__() method. Examples of subscriptable objects include strings, lists, tuples, and dictionaries.

We can check if an object implements the __getitem__() method by listing its attributes with the dir function.

If we want to check if a specific attribute belongs to an object, we can check for membership using the in operator. This approach is more straightforward than looking through the list of attributes by eye.

Let’s check if __getitem__ is an attribute of the re module and a string.

import re

attributes = dir(re)
print(type(re))
print('__getitem__' in attributes)
<class 'module'>
False

We can see that __getitem__ is not present in the list of attributes for the module re.

string = "Python"
print(type(string))
print('__getitem__' in dir(string))
<class 'str'>
True

We can see that __getitem__ is an attribute of the str class.

Example

Let’s look at an example of attempting to index a module. First, we will define a file called pizzas.py which contains a nested dictionary containing the names and information about four pizzas served in a restaurant.

pizzas_dict = {
  "margherita" : {
    "price" : 9.99,
    "is_vegetarian" : True
  },
  "pepperoni" : {
    "price" : 10.99,
    "is_vegetarian" : False
  },
  "tartufo" : {
    "price" : 13.99,
    "is_vegetarian" : False
  },
  "marinara" : {
    "price" : 7.99,
    "is_vegetarian" : True
  }
}

Next, we will try to import the pizzas module and try to retrieve the dictionary for the margherita pizza, using the key 'margherita'.

import pizzas

print(pizzas['margherita'])

Let’s run the code to see what happens:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [3], in <cell line: 1>()
----> 1 print(pizzas['margherita'])

TypeError: 'module' object is not subscriptable

The error occurred because we did not access the pizzas_dict attribute from the pizzas module and Python interprets the indexing operation as indexing the pizzas module.

Solution

We can solve the error by using the dot notation to access the pizzas_dict object. Dot notation requires a full stop followed by the name of the attribute we want to access. Let’s look at the revised code:

import pizzas

print(pizzas.pizzas_dict['margherita'])

Let’s run the code to see the result:

{'price': 9.99, 'is_vegetarian': True}

We successfully retrieved the dictionary for the margherita pizza.

We can also use the from keyword to import pizzas_dict. This approach improves the readability of the code. Let’s look at the revised code:

from pizzas import pizzas_dict

print(pizzas_dict['margherita'])

Let’s run the code to see the result:

{'price': 9.99, 'is_vegetarian': True}

We successfully retrieved the dictionary for the margherita pizza.

Summary

Congratulations on reading to the end of this tutorial!

For further reading on AttributeErrors, go to the articles:

To learn more about Python for data science and machine learning, you can go to the online courses page on Python for the most comprehensive courses.

Have fun and happy researching!

Profile Picture
Senior Advisor, Data Science | [email protected] | + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨