Cannot unpack non-iterable builtin_function_or_method object

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

Cannot unpack non-iterable builtin_function_or_method object #

The Python "TypeError: cannot unpack non-iterable builtin_function_or_method object" occurs when we try to unpack a method object instead of an iterable. To solve the error, make sure to call the method with parenthesis, e.g. my_method().

typeerror cannot unpack non iterable builtin function or method object

Here is an example of how the error occurs.

main.py
# ⛔️ TypeError: cannot unpack non-iterable builtin_function_or_method object a, b = 'one,two'.split # 👈️ forgot to call method
We forgot to call the function with parentheses, e.g. str.split(), so our code actually tries to unpack the method object and not a list.

To solve the error, make sure to call the function.

main.py
a, b = 'one,two'.split(',') print(a) # 👉️ 'one' print(b) # 👉️ 'two'

We used parentheses to invoke the method, so now we iterate over the list that the method returns.

If your method takes any arguments, you have to provide them when calling it, e.g. my_method(10, 20).

Make sure to method you are calling returns an iterable, e.g. a list or a tuple.

main.py
a, b = (10, 20) print(a) # 👉️ 10 print(b) # 👉️ 20

The variables need to be exactly as many as the values in the iterable.

main.py
a, b, c = (10, 20, 30) print(a) # 👉️ 10 print(b) # 👉️ 20 print(c) # 👉️ 30

If you aren't sure what type of object a variable stores, use the type() class.

main.py
print(type(''.split)) # 👉️ <class 'builtin_function_or_method'> print(callable(''.split)) # 👉️ True my_list = ['a', 'b', 'c'] print(type(my_list)) # 👉️ <class 'list'> print(isinstance(my_list, list)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

The callable function takes an object as an argument and returns True if the object appears callable, otherwise False is returned.

If the callable() function returns True, it is still possible that calling the object fails, however if it returns False, calling the object will never succeed.

Conclusion #

The Python "TypeError: cannot unpack non-iterable builtin_function_or_method object" occurs when we try to unpack a method object instead of an iterable. To solve the error, make sure to call the method with parenthesis, e.g. my_method().

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.