How to fix the typeerror ‘type’ object is not subscriptable error in Python?

Fix the type object is not subscriptable exception

This type error occurs when you use the bracket notation ([]) to call a Python type object. Subscriptable objects such as lists, dictionaries, strings or lists can be called using the bracket notation and their respective index. A Python class can’t. In a nutshell, you can fix this issue by instantiating your class in the following manner:

my_instance = my_class(my_args)

What is a subscriptable object?

An object is subscriptable when it contains other items / objects. For example: dictionaries, tuples, lists, sets. Integers, floats and types are not.

Understanding the Problem

Assume you have defined the following Python class:

#Python3
class language():
   
    def __init__(self, name):
        self.name = name

    def pay_level (self, salary):
        if (salary > 150):
            return print(f'{self.name} is a highly paid skill.')
        else:
            return print(f'Your {self.name} skills are very well paid, but you can probably do better.')

Let’s check the object type of this object.

type(language)

The type of a class object in Python is: type.

The type error occurs in this case when we use the bracket notation when instantiating the class.

my_lang = language['Python']

This will render the following error message in your Python development editor (PyCharm, VS Code, Spyder). Here’s a screenshot from Jupyter Labs.

Solving the type object is not subscriptable error in Python

Luckily, this one is pretty simple to solve. All you will need to do is to instantiate your class in the following fashion:

# note the parentheses instead of the brackets
my_lang = language('Python')

You will be the able to access the class properties; for example:

my_lang.name

You will be able to invoke the class methods:

my_lang.pay_level(150)

This will return the following result 🙂

Your Python skills are very well paid, but you can probably do better.

Follow up learning

How to fix the list indices must be integers Python type error?