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?
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] .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With