Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

python - Why does genexp(generator expression) is called genexp? not iterexp?

A generator is a special kind of iterator, and it has some methods that an normal iterator doesn't have such as send(), close()... etc. One can get a generator by using a genexp like below:

g=(i for i in range(3))

the type of g will be a generator. But it seems weird to me that g is a generator because g.send will do nothing since g isn't returned by a function with yield keyword, and there would be no chance for one to catch the value passed by send method(not sure this is right), I don't see a reason that g needs to be a generator instead of a more generalize type:iterator.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There seem to be some misunderstanding about definitions:

  1. Iterable is an object that implements __iter__. Also __iter__ is expected to return an iterator.
  2. Iterator is an object that implements next.
  3. Generator function is a function with yield keyword.
  4. Generator object is an object returned by a generator function. Every generator object is an iterator as well.
  5. Generator expression is a generator version of list comprehension. The result of generator expression is also called a generator object or simply a generator.

Some authors use general generator name in one of the meanings above. You have to know the context to truely understand what they are refering to. But since all those objects are closely tied there's no real problem with it.

It's always hard to answer questions "why is it like that?" when asking about naming conventions. Unless you ask the original creators its almost impossible to provide a satisfactory answer. For example it might simply be an effect of evolution and as we all know evolution does introduce errors. But here's my guess:

Both generator expressions and generator functions produce the same type of object. Now why do they produce the same object? That's probably because it was the easiest way to implement it like that under the hood. That might be the motivation.

Also note that there's a noticable difference between iterators and generator expressions: you can use yield keyword in generator expressions. Even though it is not really useful and introduces lots of confusion, the behaviour is not intuitive at all.

Resources:

https://wiki.python.org/moin/Iterator

https://wiki.python.org/moin/Generators


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...