[Python-ideas] Adding __getter__ to compliment __iter__.

Steven D'Aprano steve at pearwood.info
Fri Jul 19 19:32:15 CEST 2013


On 20/07/13 01:58, Ron Adam wrote:

> Could we have syntax for generators to bypass the method calls?
>
>      x = gen[]                 # next

Please no.

What's so special about generators that they should have magic syntax for bypassing methods? Good uses for syntax include doing things that you can't otherwise do, not as a mere alias for a method. Operators are a special case, because we want to write "1 + 1" not "(1).add(1)". But gen[] is less readable than next(gen).

Python is nice, clean and simple because it eschews vast numbers of special cases. Only a few of the most common, important features are syntax. There are more interesting ways to optimize code than adding magic syntax (e.g. PyPy, Mypy), and I doubt very much that the overhead of calling generator methods will be the bottleneck in many non-toy applications. If you're actually doing something useful with the generator data, chances are that doing that will far outweigh calling the method.

For those who really care about optimizing such calls in tight loops, there is the same option available as for any other method:

nxt = gen.__next__
for thing in tight_loop:
     x = nxt()


> Currently using empty brackets like this is a syntax error.   The brackets
> imply it is a type of iterator.  Which is the most common use for
> generators.

How do the brackets imply it is a type of iterator? To me, square brackets imply it is a list (like list displays, and list comprehensions), or sequence/mapping __getitem__.


[...]
> I think that is one of the benefits of the simple iterator design.

We already have a very simple iterator design. Making it more complex makes it less simple.


-- 
Steven


More information about the Python-ideas mailing list