Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'generator' object is not callable

I have a generator defined like this:

def lengths(x):
    for k, v in x.items():
        yield v['time_length']

And it works, calling it with

for i in lengths(x):
    print i

produces:

3600
1200
3600
300

which are the correct numbers.

However, when I call it like so:

somefun(lengths(x))

where somefun() is defined as:

def somefun(lengths):
    for length in lengths():  # <--- ERROR HERE
        if not is_blahblah(length): return False

I get this error message:

TypeError: 'generator' object is not callable

What am I misunderstanding?

like image 587
Prof. Falken Avatar asked Aug 22 '12 13:08

Prof. Falken


People also ask

How do I fix this object is not callable?

The Python "TypeError: object is not callable" occurs when we try to call a not-callable object (e.g. a list or dict) as a function using parenthesis () . To solve the error, make sure to use square brackets when accessing a list at index or a dictionary's key, e.g. my_list[0] .

What does it mean when something is not callable in Python?

The “int object is not callable” error occurs when you declare a variable and name it with a built-in function name such as int() , sum() , max() , and others. The error also occurs when you don't specify an arithmetic operator while performing a mathematical operation.

Why is my class not callable Python?

Python attempts to invoke a module as an instance of a class or as a function. This TypeError: 'module' object is not callable error occurs when class and module have the same name. The import statement imports the module name not the class name.


1 Answers

You don't need to call your generator, remove the () brackets.

You are probably confused by the fact that you use the same name for the variable inside the function as the name of the generator; the following will work too:

def somefun(lengen):
    for length in lengen:
        if not is_blahblah(length): return False

A parameter passed to the somefun function is then bound to the local lengen variable instead of lengths, to make it clear that that local variable is not the same thing as the lengths() function you defined elsewhere.

like image 76
Martijn Pieters Avatar answered Oct 07 '22 14:10

Martijn Pieters