Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
problem in using generator
#1
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
Reply
#2
In the first code, you are invoking gen()() and Python tells you that the object returned by the call gen() is not callable.
Reply
#3
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
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  list call problem in generator function using iteration and recursive calls postta 1 1,922 Oct-24-2020, 09:33 PM
Last Post: bowlofred
  Problem with Generator palladium 5 2,426 Feb-16-2020, 02:20 PM
Last Post: palladium
  receive from a generator, send to a generator Skaperen 9 5,527 Feb-05-2018, 06:26 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020