TypeError: 'generator' object is not callable in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

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 parenthesis 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 parenthesis.

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 parenthesis 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 parenthesis

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"
Use the search field on my Home Page to filter through my more than 1,000 articles.