Method object is not subscriptable ошибка

When calling a method in Python, you have to use parentheses (). If you use square brackets [], you will raise the error "TypeError: 'method' object is

When calling a method in Python, you have to use parentheses (). If you use square brackets [], you will raise the error “TypeError: ‘method’ object is not subscriptable”.

This tutorial will describe in detail what the error means. We will explore an example scenario that raises the error and learn how to solve it.

Table of contents

  • TypeError: ‘method’ object is not subscriptable
  • Example: Calling A Method With Square Brackets
    • Solution
  • Summary

TypeError: ‘method’ object is not subscriptable

TypeErrror occurs when you attempt to perform an illegal operation for a particular data type. The part “‘method’ object is not subscriptable” tells us that method is not a subscriptable object. Subscriptable objects have a __getitem__ method, and we can use __getitem__ to retrieve individual items from a collection of objects contained by a subscriptable object. Examples of subscriptable objects are lists, dictionaries and tuples. We use square bracket syntax to access items in a subscriptable object. Because methods are not subscriptable, we cannot use square syntax to access the items in a method or call a method.

Methods are not the only non-subscriptable object. Other common “not subscriptable” errors are:

  • “TypeError: ‘float’ object is not subscriptable“,
  • “TypeError: ‘int’ object is not subscriptable“
  • “TypeError: ‘builtin_function_or_method’ object is not subscriptable“
  • “TypeError: ‘function’ object is not subscriptable“

Let’s look at an example of retrieving the first element of a list using the square bracket syntax

pizzas = ["margherita", "pepperoni", "four cheeses", "ham and pineapple"]
print(pizzas[0])

The code returns:

margherita

which is the pizza at index position 0. Let’s look at an example of calling a method using square brackets.

Example: Calling A Method With Square Brackets

Let’s create a program that stores fundamental particles as objects. The Particle class will tell us the mass of a particle and its charge. Let’s create a class for particles.

class Particle:

         def __init__(self, name, mass):

             self.name = name

             self.mass = mass

         def is_mass(self, compare_mass):

             if compare_mass != self.mass:

                 print(f'The {self.name} mass is not equal to {compare_mass} MeV, it is {self.mass} MeV')

             else:

                 print(f'The {self.name} mass is equal to {compare_mass} MeV')

The Particle class has two methods, one to define the structure of the Particle object and another to check if the mass of the particle is equal to a particular value. This class could be useful for someone studying Physics and particle masses for calculations.

Let’s create a muon object with the Particle class. The mass is in MeV and to one decimal place.

muon = Particle("muon", 105.7)

The muon variable is an object with the name muon and mass value 105.7. Let’s see what happens when we call the is_mass() method with square brackets and input a mass value.

muon.is_mass[105.7]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [18], in <cell line: 1>()
----> 1 muon.is_mass[105.7]

TypeError: 'method' object is not subscriptable

We raise the TypeError because of the square brackets used to call the is_mass() method. The square brackets are only suitable for accessing items from a list, a subscriptable object. Methods are not subscriptable; we cannot use square brackets when calling this method.

Solution

We replace the square brackets with the round brackets ().

muon = Particle("muon", 105.7)

Let’s call the is_mass method with the correct brackets.

muon.is_mass(105.7)

muon.is_mass(0.51)
The muon mass is equal to 105.7 MeV

The muon mass is not equal to 0.51 MeV, it is 105.7 MeV

The code tells us the mass is equal to 105.7 MeV but is not equal to the mass of the electron 0.51 MeV.

To learn more about correct class object instantiation and calling methods in Python go to the article titled “How to Solve Python missing 1 required positional argument: ‘self’“.

Summary

Congratulations on reading to the end of this tutorial! The error “TypeError: ‘method’ object is not subscriptable” occurs when you use square brackets to call a method. Methods are not subscriptable objects and therefore cannot be accessed like a list with square brackets. To solve this error, replace the square brackets with the round brackets after the method’s name when you are calling it.

To learn more about Python for data science and machine learning, go to the online courses page on Python for the best courses available!

Have fun and happy researching!

Arguments in Python methods must be specified within parentheses. This is because functions and methods both use parentheses to tell if they are being called. If you use square brackets to call a method, you’ll encounter an “TypeError: ‘method’ object is not subscriptable” error.

In this guide, we discuss what this error means and why you may encounter it. We walk through an example of this error to help you develop a solution.

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.

TypeError: ‘method’ object is not subscriptable

Subscriptable objects are objects with a __getitem__ method. These are data types such as lists, dictionaries, and tuples. The __getitem__ method allows the Python interpreter to retrieve an individual item from a collection.

Not all objects are subscriptable. Methods, for instance, are not. This is because they do not implement the __getitem__ method. This means you cannot use square bracket syntax to access the items in a method or to call a method.

Consider the following code snippet:

cheeses = ["Edam", "Stilton", "English Cheddar", "Parmesan"]
print(cheeses[0])

This code returns “Edam”, the cheese at the index position 0. We cannot use square brackets to call a function or a method because functions and methods are not subscriptable objects.

An Example Scenario

Here, we build a program that stores cheeses in objects. The “Cheese” class that we use to define a cheese will have a method that lets us check whether a cheese is from a particular country of origin.

Start by defining a class for our cheeses. We call this class Cheese:

class Cheese:
	def __init__(self, name, origin):
		self.name = name
		self.origin = origin

	def get_country(self, to_compare):
		if to_compare == self.origin:
			print("{} is from {}.".format(self.name, self.origin))
		else:
			print("{} is not from {}. It is from {}.".format(self.name, to_compare, self.origin))

Our class contains two methods. The first method defines the structure of the Cheese object. The second lets us check whether the country of origin of a cheese is equal to a particular value. 

Next, we create an object from our Cheese class:

edam = Cheese("Edam", "Netherlands")

The variable “edam” is an object. The name associated with the cheese is Edam and its country of origin is the Netherlands.

Next, let’s call our get_country() method:

edam.get_country["Germany"]

This code executes the get_country() method from the Cheese class. The get_country() method checks whether the value of “origin” in our “edam” object is equal to “Germany”.

Run our code and see what happens:

Traceback (most recent call last):
  File "main.py", line 14, in <module>
	edam.get_country["Germany"]
TypeError: 'method' object is not subscriptable

An error occurs in our code.

The Solution

Let’s analyze the line of code that the Python debugger has identified as erroneous:

edam.get_country["Germany"]

In this line of code, we use square brackets to call the get_country() method. This is not acceptable syntax because square brackets are used to access items from a list. Because functions and objects are not subscriptable, we cannot use square brackets to call them.

To solve this error, we must replace the square brackets with curly brackets:

edam.get_country("Germany")

Let’s run our code and see what happens:

Edam is not from Germany. It is from Netherlands.

Our code successfully executes. Let’s try to check whether Edam is from “Netherlands” to make sure our function works in all cases, whether or not the value we specify is equal to the cheese’s origin country:

edam.get_country("Netherlands")

Our code returns:

Edam is from Netherlands.

Our code works if the value we specify is equal to the country of origin of a cheese.

Conclusion

The “TypeError: ‘method’ object is not subscriptable” error is raised when you use square brackets to call a method inside a class. To solve this error, make sure that you only call methods of a class using curly brackets after the name of the method you want to call.

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

TypeError: builtin_function_or_method object is not subscriptable Python Error [SOLVED]

As the name suggests, the error TypeError: builtin_function_or_method object is not subscriptable is a “typeerror” that occurs when you try to call a built-in function the wrong way.

When a «typeerror» occurs, the program is telling you that you’re mixing up types. That means, for example, you might be concatenating a string with an integer.

In this article, I will show you why the TypeError: builtin_function_or_method object is not subscriptable occurs and how you can fix it.

Every built-in function of Python such as print(), append(), sorted(), max(), and others must be called with parenthesis or round brackets (()).

If you try to use square brackets, Python won’t treat it as a function call. Instead, Python will think you’re trying to access something from a list or string and then throw the error.

For example, the code below throws the error because I was trying to print the value of the variable with square braces in front of the print() function:

And if you surround what you want to print with square brackets even if the item is iterable, you still get the error:

gadgets = ["Mouse", "Monitor", "Laptop"]
print[gadgets[0]]

# Output: Traceback (most recent call last):
#   File "built_in_obj_not_subable.py", line 2, in <module>
#     print[gadgets[0]]
# TypeError: 'builtin_function_or_method' object is not subscriptable

This issue is not particular to the print() function. If you try to call any other built-in function with square brackets, you also get the error.

In the example below, I tried to call max() with square brackets and I got the error:

numbers = [5, 7, 24, 6, 90]
max_num = max(numbers)
print[max_num]

# Traceback (most recent call last):
#   File "built_in_obj_not_subable.py", line 11, in <module>
#     print[max_num]
# TypeError: 'builtin_function_or_method' object is not subscriptable

How to Fix the TypeError: builtin_function_or_method object is not subscriptable Error

To fix this error, all you need to do is make sure you use parenthesis to call the function.

You only have to use square brackets if you want to access an item from iterable data such as string, list, or tuple:

gadgets = ["Mouse", "Monitor", "Laptop"]
print(gadgets[0])

# Output: Mouse
numbers = [5, 7, 24, 6, 90]
max_num = max(numbers)
print(max_num)

# Output: 90

Wrapping Up

This article showed you why the TypeError: builtin_function_or_method object is not subscriptable occurs and how to fix it.

Remember that you only need to use square brackets ([]) to access an item from iterable data and you shouldn’t use it to call a function.

If you’re getting this error, you should look in your code for any point at which you are calling a built-in function with square brackets and replace it with parenthesis.

Thanks for reading.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

In Python, Built-in functions are not subscriptable, if we use the built-in functions as an array to perform operations such as indexing, you will encounter TypeError: ‘builtin_function_or_method’ object is not subscriptable.

This article will look at what TypeError: ‘builtin_function_or_method’ object is not subscriptable error means and how to resolve this error with examples.

If we use the square bracket [] instead of parenthesis() while calling a function, Python will throw TypeError: ‘builtin_function_or_method’ object is not subscriptable.

The functions in Python are called using the parenthesis “()", and that’s how we distinguish the function call from the other operations, such as indexing the list. Usually, when working with lists or arrays, it’s a common mistake that the developer makes. 

Let us take a simple example to reproduce this error.

Here in the example below, we have a list of car brands and are adding the new car brand to the list.

We can use the list built-in function to add a new car brand to the list, and when we execute the code, Python will throw TypeError: ‘builtin_function_or_method’ object is not subscriptable.

cars = ['BMW', 'Audi', 'Ferrari', 'Benz']

# append the new car to the list
cars.append["Ford"]

# print the list of new cars
print(cars)

Output

Traceback (most recent call last):
  File "c:PersonalIJSCodemain.py", line 4, in <module>
    cars.append["Ford"]
TypeError: 'builtin_function_or_method' object is not subscriptable

We are getting this error because we are not correctly using the append() method. We are indexing it as if it is an array (using the square brackets), but in reality, the append() is a built-in function.

How to Fix TypeError: ‘builtin_function_or_method’ object is not subscriptable?

We can fix the above code by treating the append() as a valid function instead of indexing.

In simple terms, we need to replace the square brackets with the parentheses (), making it a proper function.

This happens while working with arrays or lists and using functions like append(), pop(), remove(), etc., and if we perform the indexing operation using the function.

After replacing the code, you can observe that it runs successfully and adds a new brand name as the last element to the list.

cars = ['BMW', 'Audi', 'Ferrari', 'Benz']

# append the new car to the list
cars.append("Ford")

# print the list of new cars
print(cars)

Output

['BMW', 'Audi', 'Ferrari', 'Benz', 'Ford']

Conclusion

The TypeError: ‘builtin_function_or_method’ object is not subscriptable occurs if we use the square brackets instead of parenthesis while calling the function. 

The square brackets are mainly used to access elements from an iterable object such as list, array, etc. If we use the square brackets on the function, Python will throw a TypeError.

We can fix the error by using the parenthesis while calling the function.

Avatar Of Srinivas Ramakrishna

Srinivas Ramakrishna is a Solution Architect and has 14+ Years of Experience in the Software Industry. He has published many articles on Medium, Hackernoon, dev.to and solved many problems in StackOverflow. He has core expertise in various technologies such as Microsoft .NET Core, Python, Node.JS, JavaScript, Cloud (Azure), RDBMS (MSSQL), React, Powershell, etc.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

By checking this box, you confirm that you have read and are agreeing to our terms of use regarding the storage of the data submitted through this form.

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

Понравилась статья? Поделить с друзьями:
  • Method miio info error on socket receive ошибка
  • Method local is set but never used local1 как исправить
  • Method invocation error
  • Method get status error on socket receive xiaomi пылесос что делать
  • Method get status error on socket receive xiaomi vacuum что делать