Python Forum
problem in using generator - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: problem in using generator (/thread-41075.html)



problem in using generator - akbarza - Nov-07-2023

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


RE: problem in using generator - Gribouillis - Nov-07-2023

In the first code, you are invoking gen()() and Python tells you that the object returned by the call gen() is not callable.


RE: problem in using generator - perfringo - Nov-07-2023

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