TypeError: 'generator' object is not callable

天大地大妈咪最大 提交于 2021-02-07 11:23:21

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/12074726/typeerror-generator-object-is-not-callable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!