TypeError: 'generator' object is not callable in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: 'generator' object is not callable in Python #

The Python "TypeError: 'generator' object is not callable" occurs when we try to call a generator object as if it were a function. To solve the error, remove the parentheses and make sure you don't have any clashes between function and variable names.

typeerror generator object is not callable

Here is an example of how the error occurs

main.py
def g(): yield 1 yield 2 yield 3 gen = g() print(type(gen)) # 👉️ <class 'generator'> # ⛔️ TypeError: 'generator' object is not callable print(gen())

We tried to call a generator object as a function which caused the error.

To solve the error, remove the parentheses.

main.py
def g(): yield 1 yield 2 yield 3 gen = g() # 👈️ creates generator for i in gen: print(i) # 👉️ 1, 2, 3

Alternatively, you can pass the generator to the next() function to retrieve the next item.

main.py
def g(): yield 1 yield 2 yield 3 gen = g() print(next(gen)) # 👉️ 1 print(next(gen)) # 👉️ 2 print(next(gen)) # 👉️ 3

Make sure you don't have an extra set of parentheses when creating the generator.

main.py
def g(): yield 1 yield 2 yield 3 # ⛔️ TypeError: 'generator' object is not callable gen = g()() # 👈️ remove extra set of parentheses

Another common cause of the error is having a clash between variable and function names.

main.py
def g(): yield 1 yield 2 yield 3 def gen(): return 'hello world' gen = g() # ⛔️ TypeError: 'generator' object is not callable gen()

The gen variable shadows the gen() function, so when we try to call the function, we end up calling the variable.

To solve the error, rename the variable or the function.

main.py
def g(): yield 1 yield 2 yield 3 def greet(): return 'hello world' gen = g() print(greet()) # 👉️ "hello world"

Conclusion #

The Python "TypeError: 'generator' object is not callable" occurs when we try to call a generator object as if it were a function. To solve the error, remove the parentheses and make sure you don't have any clashes between function and variable names.

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.