PEP 234: Iterators
Christian Tanzer
tanzer at swing.co.at
Tue May 1 03:18:54 EDT 2001
> for line in file:
> ...
Cool.
> Among its chief virtues are the following three -- no, four -- no,
> five -- points:
I'd add:
6. It makes code iterating over non-sequences more concise and
readable.
> - The name iter() is an abbreviation. Alternatives proposed
> include iterate(), harp(), traverse(), narrate().
IMHO, a verb conveys the wrong meaning because the function returns
an iterator object -- it doesn't iterate over anything itself.
The clearest name for this function would be `iterator' <surprise>,
but `iter' would work just as well as `len', `str', `repr', and all the
other abbreviated builtins do.
`harp' and the like are just silly -- whoever wants to use an
obfuscated programming language probably knows where to get it.
> - Using the same name for two different operations (getting an
> iterator from an object and making an iterator for a function
> with an sentinel value) is somewhat ugly. I haven't seen a
> better name for the second operation though.
I assume `ugly' refers to the implementation.
As both operations return an iterator object it seems natural to use
the same name for them. Having to remember two different names for
iterator-returning operations looks ugly to me.
> - There is still discussion about whether
>
> for x in dict: ...
>
> should assign x the successive keys, values, or items of the
> dictionary. The symmetry between "if x in y" and "for x in y"
> suggests that it should iterate over keys. This symmetry has been
> observed by many independently and has even been used to "explain"
> one using the other. This is because for sequences, "if x in y"
> iterates over y comparing the iterated values to x. If we adopt
> both of the above proposals, this will also hold for
> dictionaries.
If `if x in dict' is implemented (which I hope) making `for x in dict'
iterate over something other than the keys would be very confusing.
> We could also add methods to dictionaries that return different kinds
> of iterators
Please do so.
for k, v in dict.itemiter():
...
is both more readable and more efficient than
for k in dict:
v = dict[k]
...
The item-iterator can also be passed around whereas the other form
cannot.
--
Christian Tanzer tanzer at swing.co.at
Glasauergasse 32 Tel: +43 1 876 62 36
A-1130 Vienna, Austria Fax: +43 1 877 66 92
More information about the Python-list
mailing list