[Python-Dev] Propose updating PEP 284 -- Integer for-loops
Raymond Hettinger
raymond.hettinger at verizon.net
Sat Jun 18 10:45:32 CEST 2005
I recommend that the proposed syntax be altered to be more parallel with
the existing for-loop syntax to make it more parsable for both humans
and for the compiler. Like existing for-statements, the target
expression should immediately follow the 'for' keyword. Since this is
known to be a range assignment, only an expression is needed, not a full
expression list. Immediately following should be a token to distinguish
the new and old syntaxes. Putting that distinction early in the
statement prepares readers (who scan left-to-right) for what follows.
IOW, augment the existing syntax:
for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]
with an alternative syntax in the form:
for_stmt: 'for' expr 'tok' rangespec ':' suite ['else' ':' suite]
Given that form, the PEP authors can choose the best options for 'tok'.
Basically, anything will do as long as it is not 'in'. Likewise, they
can choose any rangespec format. Within that framework, there are many
possibilities:
for i between 2 < i <= 10: ...
for i over 2 < i <= 10: ... # chained comparison style
for i over [2:11]: ... # Slice style
for i = 3 to 10: ... # Basic style
The rangespecs with comparison operators offer more flexibility in terms
of open/closed intervals. In contrast, the slice notation version and
the Basic versions can admit a step argument.
The key changes are stating the target variable first and then using a
specific token to distinguish between the two forms.
Also, I recommend tightening the PEP's motivation. There are only two
advantages, encoding and readability. The former is only a minor gain
because all it saves is a function call, an O(1) savings in an O(n)
context. The latter is where the real benefits lay.
The PEP authors should also put to rest the issues section:
* Decide once and for all on the simplest approach of immediately
evaluating the whole rangespec prior to execution. This best parallels
the range() approach and it is the least surprising.
* Note that new proposal works equally well with list comps and genexps.
* Decide to always return an iterator rather than a list as there is
never an advantage to doing otherwise.
* If you go for a chained comparison style rangespec, then drop the
issue of a step argument. If the slice or Basic style rangespecs are
chosen, then there is no reason not to allow a step argument.
* Competition with PEP 276 is no longer an issue.
* Simply disallow floating point bounds. We've already got deprecation
warnings in place for Py2.5. There is no need to exacerbate the
problem. Alternately, simplify the issue by declaring that the values
will be handled as if by xrange().
The above recommendations should get the PEP ready for judgement day.
Good luck.
Raymond
More information about the Python-Dev
mailing list