TypeError: cannot unpack non-iterable function object

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: cannot unpack non-iterable function object #

The Python "TypeError: cannot unpack non-iterable function object" occurs when we try to unpack a function object instead of an iterable. To solve the error, make sure to call the function with parentheses, e.g. my_function() and return an iterable from the function.

typeerror cannot unpack non iterable function object

Here is an example of how the error occurs.

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

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

main.py
def get_list(): return ['one', 'two'] a, b = get_list() print(a) # 👉️ 'one' print(b) # 👉️ 'two'

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

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

Make sure to return an iterable from the function, 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
def get_list(): return ['one', 'two'] print(type(get_list)) # 👉️ <class 'function'> print(callable(get_list)) # 👉️ 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 function object" occurs when we try to unpack a function object instead of an iterable. To solve the error, make sure to call the function with parentheses, e.g. my_function() and return an iterable from the function.

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.