Typeerror function object is not subscriptable ошибка

Understanding the problem in more detail

Hopefully, it will not be surprising that this code causes a (different) TypeError:

>>> example = 1
>>> example = "not an integer"
>>> example + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

A name can only refer to one thing at a time; when we start using it for something else, it’s no longer used for the first thing. When the addition is attempted, there is not an ambiguity between example meaning the integer or the string: it definitely means the string. (Of course, we can cause other kinds of errors by reusing a name, too. However, my guess is that TypeError is the most common kind of error here. After all — if we reused the name for something of the same type, isn’t that more likely to be intentional?)

What’s sometimes less obvious — especially for programmers who were taught with traditional terminology like «variable», rather than Python-appropriate terminology like «name» — is that there are other ways to assign a name, besides the assignment operator.

In Python, everything is an object, and we take that seriously. Unlike in, say, Java, Python’s functions, classes, and modules are objects — which means, among other things, that they have the same kind of names that integers and strings do.

Writing def example(): pass is creating an object that is a function (it doesn’t merely represent the function for use in reflection; it really is already, itself, an object), and assigns it to the name example. Which means, if there was something else — say, a list — with the same name in the same scope, that other object no longer has that name. It’s been reused. Functions don’t get a separate scope or a separate namespace. They have the same kind of names as everything else; they aren’t special. (Remember, Python figures out types at runtime, and «function» is just another type.)

So, if we create a list and then try to create a function with the same name, we can’t index into the list with that name — because the name is used for the function, not the list any more. Similarly the other way around: if we write the function (or the function already exists, because it’s a builtin) and then try to use its name for something else, we can’t call the original function any more. If we used the name for something that isn’t callable, we can’t use that name to call anything.


Here are some other examples of ways to assign names, with thanks to https://nedbatchelder.com/text/names1.html. In each case, example is the name that gets assigned.

  • Using the name for iteration in a for loop or a comprehension or generator expression (for example in data:, [f(example) for example in data] etc. In a generator expression, of course, the name is only assigned when an element is requested from the generator)

  • Calling a function (supposing we have def func(example): pass, then func(1) does the assignment)

  • Making a class (class Example: — hopefully this is not surprising, since we already noted that classes are objects)

  • Importing a module (import example), or a module’s contents (from my.package import example) etc. (Hopefully this is not surprising, since we already noted that modules are objects. Incidentally, packages are objects too, but Python represents them with the same module type)

  • The as clause when handling an exception (except Exception as example:) or using a context manager (with open('example.txt') as example:)

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.

Table of contents

  • TypeError: ‘function’ object is not subscriptable
    • What is a TypeError?
    • What Does Subscriptable Mean?
  • Example #1: Calling a Function Using Square Brackets
    • Solution
  • Example #2: Function has the Same Name as a Subscriptable object
    • Solution
  • Summary

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:

  • How to Solve Python TypeError: ‘NoneType’ object is not subscriptable
  • How to Solve Python TypeError: ‘map’ object is not subscriptable

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

Have fun and happy researching!

Unlike iterable objects, you cannot access a value from a function using indexing syntax.

Even if a function returns an iterable, you must assign the response from a function to a variable before accessing its values. Otherwise, you encounter an “TypeError: ‘function’ object is not subscriptable” error.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

In this guide, we talk about what this error means. We walk through two examples of this error so you can figure out how to solve it in your code.

TypeError: ‘function’ object is not subscriptable

Iterable objects such as lists and strings can be accessed using indexing notation. This lets you access an individual item, or range of items, from an iterable.

Consider the following code:

grades = ["A", "A", "B"]
print(grades[0])

The value at the index position 0 is A. Thus, our code returns “A”. This syntax does not work on a function. This is because a function is not an iterable object. Functions are only capable of returning an iterable object if they are called.

The “TypeError: ‘function’ object is not subscriptable” error occurs when you try to access a function as if it were an iterable object.

This error is common in two scenarios:

  • When you assign a function the same name as an iterable
  • When you try to access the values from a function as if the function were iterable

Let’s analyze both of these scenarios.

Scenario #1: Function with Same Name as an Iterable

Create a program that prints out information about a student at a school. We start by defining a dictionary with information on a student and their latest test score:

student = { "name": "Holly", "latest_test_score": "B", "class": "Sixth Grade" }

Our dictionary contains three keys and three values. One key represents the name of a student; one key represents the score a student earned on their latest test; one key represents the class a student is in.

Next, we’re going to define a function that prints out these values to the console:

def student(pupil):
	print("Name: " + pupil["name"])
	print("Latest Test Score: " + pupil["latest_test_score"])
	print("Class: " + pupil["class"])

Our code prints out the three values in the “pupil” dictionary to the console. The “pupil” dictionary is passed as an argument into the student() function.

Let’s call our function and pass the “student” dictionary as a parameter:

Our Python code throws an error:

Traceback (most recent call last):
  File "main.py", line 8, in <module>
	student(student)
  File "main.py", line 4, in student
	print("Name: " + pupil["name"])
TypeError: 'function' object is not subscriptable

This error is caused because we have a function and an iterable with the same name. “student” is first declared as a dictionary. We then define a function with the same name. This makes “student” a function rather than a dictionary.

When we pass “student” as a parameter into the student() function, we are passing the function with the name “student”.

We solve this problem by renaming our student function:

def show_student_details(pupil):
	print("Name: " + pupil["name"])
	print("Latest Test Score: " + pupil["latest_test_score"])
	print("Class: " + pupil["class"])

show_student_details(student)

We have renamed our function to “show_student_details”. Let’s run our code and see what happens:

Name: Holly
Latest Test Score: B
Class: Sixth Grade

Our code successfully prints out information about our student to the console.

Scenario #2: Accessing a Function Using Indexing

Write a program that filters a list of student records and only shows the ones where a student has earned an A grade on their latest test.

We’ll start by defining an array of students:

students = [
	{ "name": "Holly", "grade": "B" },
	{ "name": "Samantha", "grade": "A" },
	{ "name": "Ian", "grade": "A" }
]

Our list of students contains three dictionaries. Each dictionary contains the name of a student and the grade they earned on their most recent test.

Next, define a function that returns a list of students who earned an A grade:

def get_a_grade_students(pupils):
	a_grade_students = []
	for p in pupils:
    		if p["grade"] == "A":
        			a_grade_students.append(p)

	print(a_grade_students)

	return a_grade_students

The function accepts a list of students called “pupils”. Our function iterates over that list using a for loop. If a particular student has earned an “A” grade, their record is added to the “a_grade_students” list. Otherwise, nothing happens.

Once all students have been searched, our code prints a list of the students who earned an “A” grade and returns that list to the main program.

We want to retrieve the first student who earned an “A” grade. To do this, we call our function and use indexing syntax to retrieve the first student’s record:

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

first = get_a_grade_students[0]

print(first)

Run our code:

Traceback (most recent call last):
  File "main.py", line 16, in <module>
	first = get_a_grade_students[0]
TypeError: 'function' object is not subscriptable

Our code returns an error. We’re trying to access a value from the “get_a_grade_students” function without first calling the function.

To solve this problem, we should call our function before we try to retrieve values from it:

a_grades = get_a_grade_students(students)
first = a_grades[0]

print(first)

First, we call our get_a_grade_students() function and specify our list of students as a parameter. Next, we use indexing to retrieve the record at the index position 0 from the list that the get_a_grade_students() function returns. Finally, we print that record to the console.

Let’s execute our code:

[{'name': 'Samantha', 'grade': 'A'}, {'name': 'Ian', 'grade': 'A'}]
{'name': 'Samantha', 'grade': 'A'}

Our code first prints out a list of all students who earned an “A” grade. Next, our code prints out the first student in the list who earned an “A” grade. That student was Samantha in this case.

Conclusion

The “TypeError: ‘function’ object is not subscriptable” error is raised when you try to access an item from a function as if the function were an iterable object, like a string or a list.

To solve this error, first make sure that you do not override any variables that store values by declaring a function after you declare the variable. Next, make sure that you call a function first before you try to access the values it returns.

Now you’re ready to solve this common Python error like a professional coder!

The typeerror: function object is not subscriptable error generates because of using indexes while invoking functional object. Generally, Functions are callable object but not subscriptible. In this article, we will see the best ways to fix this error. We will also try to understand the situations where usually this error occurs. So Lets go !!

Lets practically understand the context for this error.

def print_name(name):
  print(name)
  return name + " Data Science Learner "

var=print_name[0]

Here print_name is callable function. But we are not invoking it as function with parameter. IN the place of it we used index print_name[0]. Hence when we run this code , we get function object is not subscriptable python error.

typeerror function object is not subscriptable root cause

typeerror function object is not subscriptable root cause

typeerror: function object is not subscriptable (   Solution ) –

The fix for this error is simple to avoid calling function using indexes. But you already know about it. So what next ? See lets simplify this for us with scenarios.-

Case 1:  name ambiguity in function and iterable object –

This is one of the very common scenario for this error. Here we use the same name for function and iterable objects like ( list , dict, str etc)  . If we declare the iterable object first and then function, so function will overwrite the iterable object type and throughs the same error.

print_name=[1,2,3]

def print_name(name):
  print(name)
  return name + " Data Science Learner "

var=print_name[0]

function object is not subscriptable solution for name ambiguity

function object is not subscriptable solution for name ambiguity

Hence we should always provide unique name to each identifiers. If we follow this best practice, we will never get this kind of error.

Case 2 : avoiding functions returns with local assignment-

If any function is returning any iterable object but we are not assigning it into any local variable. Wile directly accessing it with indexes it throws the same type error. Lets see how –

function object is not subscriptable solution

function object is not subscriptable solution

To avoid this we can follow the the below way –

def fun():
  data=[1,2,3]
  return  data

temp=fun()
var=temp[0]
print(var)

Similar Errors :

Typeerror: type object is not subscriptable ( Steps to Fix)

Solution -Typeerror int object is not subscriptable 

Typeerror nonetype object is not subscriptable : How to Fix 

Thanks
Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Object Is Not Subscriptable

Overview

Example errors:

TypeError: object is not subscriptable

Specific examples:

  • TypeError: 'type' object is not subscriptable
  • TypeError: 'function' object is not subscriptable
Traceback (most recent call last):
  File "afile.py", line , in aMethod
    map[value]
TypeError: 'type' object is not subscriptable

This problem is caused by trying to access an object that cannot be indexed as though it can be accessed via an index.

For example, in the above error, the code is trying to access map[value] but map is already a built-in type that doesn’t support accessing indexes.

You would get a similar error if you tried to call print[42], because print is a built-in function.

Initial Steps Overview

  1. Check for built-in words in the given line

  2. Check for reserved words in the given line

  3. Check you are not trying to index a function

Detailed Steps

1) Check for built-in words in the given line

In the above error, we see Python shows the line

This is saying that the part just before [value] can not be subscripted (or indexed). In this particular instance, the problem is that the word map is already a builtin identifier used by Python and it has not been redefined by us to contain a type that subscripts.

You can see a full list of built-in identifiers via the following code:

# Python 3.0
import builtins
dir(builtins)

# For Python 2.0
import __builtin__
dir(__builtin__)

2) Check for instances of the following reserved words

It may also be that you are trying to subscript a keyword that is reserved by Python True, False or None

>>> True[0]
<stdin>:1: SyntaxWarning: 'bool' object is not subscriptable; perhaps you missed a comma?
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'bool' object is not subscriptable

3) Check you are not trying to access elements of a function

Check you are not trying to access an index on a method instead of the results of calling a method.

txt = 'Hello World!'

# Incorrectly getting the first word
>>> txt.split[0]

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'builtin_function_or_method' object is not subscriptable

# The correct way
>>> txt.split()[0]

'Hello'

You will get a similar error for functions/methods you have defined yourself:

def foo():
    return ['Hello', 'World']

# Incorrectly getting the first word
>>> foo[0]

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'function' object is not subscriptable

# The correct way
>>> foo()[0]
'Hello'

Solutions List

A) Initialize the value

B) Don’t shadow built-in names

Solutions Detail

A) Initialize the value

Make sure that you are initializing the array before you try to access its index.

map = ['Hello']
print(map[0])

Hello

B) Don’t shadow built-in names

It is generally not a great idea to shadow a language’s built-in names as shown in the above solution as this can confuse others reading your code who expect map to be the builtin map and not your version.

If we hadn’t used an already taken name we would have also got a much more clear error from Python, such as:

>>> foo[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'foo' is not defined

But don’t just take our word for it: see here

Further Information

  • Python 2: Subscriptions
  • Python 3: Subscript notation

@Gerry

comments powered by

  • Type module js ошибка
  • Type mismatch vba excel ошибка runtime 13
  • Type mismatch vba access ошибка
  • Tylo cc50 ошибка 003
  • Txd workshop ошибка при открытии hud txd для gta sa