Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
problem in using generator
after running the code:
def gen():
    for i in range(3):
        yield i*i

for i in g1():
the below error will be shown in the output:
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():
then the output will be:
0 1 4
or if the code will be changed to:
for i in g1:
then the last true output is displayed again.
what is the reason for this? plz, explain.
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()
>>> 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()()
>>> a = return_callable()
>>> a()
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.

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

Forum Jump:

User Panel Messages

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