Python Forum

Full Version: problem in using generator
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hi
after running the code:
def gen():
    for i in range(3):
        yield i*i
    return

g1=gen()
for i in g1():
    print(i)
the below error will be shown in the output:
Error:
Traceback (most recent call last): File "<pyshell#36>", line 1, in <module> for i in g1(): TypeError: 'generator' object is not callable
but if i use gen()itself , namely:
for i in gen():
    print(i)
then the output will be:
Output:
0 1 4
or if the code will be changed to:
g1=gen()
for i in g1:
    print(i)
then the last true output is displayed again.
what is the reason for this? plz, explain.
thanks
In the first code, you are invoking gen()() and Python tells you that the object returned by the call gen() is not callable.
This is not generator specific.

() signals to Python that this is a callable object and should be called. Python tries to do it.

If you call it second time then it depends what first callable returned. To illustrate:

>>> def literal():
...     return 'a'
...
>>> literal()
'a'
>>> literal()()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
No good - literal function returned str and it's not callable. TypeError is raised.

However, if function returns another function (which is callable) then it works:

>>> def num():
...     return 42
...
>>> def return_callable():
...     return num
...
>>> return_callable()()
42
>>> a = return_callable()
>>> a()
42