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

by | Programming, Python, Tips

In Python, a function is a block of code that only runs when called. You can pass data, known as parameters or arguments, to a function, and a function can return data as a result. To call a function, you must use the function name followed by parentheses () and pass the arguments inside the parentheses separated by commas. If you try to call a function using square brackets [] instead of parentheses, you will raise the error: “TypeError: ‘function’ object is not subscriptable”.

This tutorial will go through the error in detail. We will go through two example scenarios of this error and learn to solve it.

TypeError: ‘function’ object is not subscriptable

What is a TypeError?

A TypeError occurs when you perform an illegal operation for a specific data type.

What Does Subscriptable Mean?

The subscript operator, which is square brackets [], retrieves items from subscriptable objects like lists or tuples. The operator in fact calls the __getitem__ method, for example, a[i] is equivalent to a.__getitem__(i).

All subscriptable objects have a __getitem__ method. Functions do not contain items and do not have a __getitem__ method. We can verify that functions objects do not have the __getitem__ method by defining a function and passing it to the dir() method:

def add(a, b):
   result = a + b
   return result

print(type(add))

print(dir(add))
<class 'function'>

['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Let’s look at an example of accessing an item from a list:

numbers = [0, 1, 2, 3, 4]

print(numbers[2])
2

The value at the index position 2 is 2. Therefore, the code returns 2.

Functions are not subscriptable. Therefore, you cannot use square syntax to access the items in a function or to call a function, and functions can only return a subscriptable object if we call them.

The error “TypeError: ‘function’ object is not subscriptable” occurs when you try to access a function as if it were a subscriptable object. There are two common mistakes made in code that can raise this error.

  • Calling a function using square brackets
  • Assigning a function the same name as a subscriptable object

Example #1: Calling a Function Using Square Brackets

You can call a function using parentheses after the function name, and indexing uses square brackets after the list, tuple, or string name. If we put the indexing syntax after a function name, the Python interpreter will try to perform the indexing operation on the function. Function objects do not support the indexing operation, and therefore the interpreter will throw the error.

Let’s look at an example of creating a function that takes two integers as arguments and raises the first integer to the power of the second integer using the exponentiation operator **. First, you define the exponent function, then define two integer values to pass to the function. Then you will print the result of the exponent function.

# Exponent function

def exponent(a, b):

    return a ** b

a = 4

b = 3

print(f'{a} raised to the power of {b} is: {exponent[a, b]}')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [2], in <cell line: 11>()
      7 a = 4
      9 b = 3
---> 11 print(f'{a} raised to the power of {b} is: {exponent[a, b]}')

TypeError: 'function' object is not subscriptable

The code did not run because you tried to call the exponent function using square brackets.

Solution

You need to replace the square brackets after the exponent name with parentheses to solve the problem.

# Exponent function

def exponent(a, b):

    return a ** b

a = 4

b = 3

print(f'{a} raised to the power of {b} is: {exponent(a, b)}')
4 raised to the power of 3 is: 64

The code runs successfully with the correct syntax to call a function in place.

Example #2: Function has the Same Name as a Subscriptable object

You may encounter this TypeError if you define a subscriptable object with the same name as a function. Let’s look at an example where we define a dictionary containing information about the fundamental physical particle, the muon.

particle = {

   "name":"Muon",

   "charge":-1,

   "spin":1/2,

   "mass":105.7

}

Next, we are going to define a function that prints out the values of the dictionary to the console:

def particle(p):
   
   print(f'Particle Name: {p["name"]}')
   
   print(f'Particle Charge: {p["charge"]}')
   
   print(f'Particle Spin: {p["spin"]}')
   
   print(f'Particle Mass: {p["mass"]}')

Next, we will call the particle function and pass the particle dictionary as a parameter:

particle(particle)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [5], in <cell line: 1>()
----> 1 particle(particle)

Input In [4], in particle(p)
      1 def particle(p):
----> 3    print(f'Particle Name: {p["name"]}')
      5    print(f'Particle Charge: {p["charge"]}')
      7    print(f'Particle Spin: {p["spin"]}')

TypeError: 'function' object is not subscriptable

We raise this error because we have a function and a subscriptable object with the same name. We first declare “particle” as a dictionary, and then we define a function with the same name, which makes “particle” a function rather than a dictionary. Therefore, when we pass “particle” as a parameter to the particle() function, we are passing the function with the name “particle“. Square brackets are used within the code block to access items in the dictionary, but this is done on the function instead.

Solution

To solve this problem, we can change the name of the function. It is good to change the function name to describe what the function does. In this case, we will rename the function to show_particle_details().

particle = {

   "name":"Muon",

   "charge":-1,

   "spin":1/2,

   "mass":105.7

}
def show_particle_details(p):
   
   print(f'Particle Name: {p["name"]}')
   
   print(f'Particle Charge: {p["charge"]}')
   
   print(f'Particle Spin: {p["spin"]}')
   
   print(f'Particle Mass: {p["mass"]}')

Let’s see what happens when we try to run the code:

show_particle_details(particle)
Particle Name: Muon

Particle Charge: -1

Particle Spin: 0.5

Particle Mass: 105.7

The code runs successfully and prints out the particle information to the console.

Summary

Congratulations on reading to the end of this tutorial. The error “TypeError: ‘function’ object is not subscriptable” occurs when you try to access an item from a function. Functions cannot be indexed using square brackets.

To solve this error, ensure functions have different names to variables. Always call a function before attempting to access the functions. When you call a function using parentheses and not square brackets, the function returns.

For further reading on TypeErrors, go to the articles:

Go to the online courses page on Python to learn more about Python for data science and machine learning.

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 ✨