简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM