Some Python 2.1 ideas
bobalex at home.com
Sat Dec 23 18:00:25 CET 2000
Here are some thoughts on possible enhancements to Python. If discussion
shows any positive enthusiasm maybe they could turn into PEPs.
New operator: embedded assignment
As C and Java programmers know, it is sometimes more expressive to embed
assignments inside other expressions. It's my guess that one reason Python
doesn't support this is to make "=" illegal inside expressions, thus
avoiding the "=" vs. "==" errors common in C. A response to that objection
is to use a different token for embedded assignment -- I suggest ":=" since
it's already familiar to many folks as an assignment operator. Then instead
line = f.readline()
if not line:
print line # yes, this will double space, but see another
suggestion below :-)
We could code:
while line := f.readline():
There are many such cases where "assignment as an operator" can make
programs more compact and expressive.
Is there a downside? The only one I can think of is that assignment targets
would not always appear at the left end of program lines!
- Introduce a new binary operator of low precedence and right
associativity, x := y, which assigns y to x and returns y.
- "if x = y: ..." still produces an error, but "if "x := y: ..." does
Variations on "for"
Here are some possible additional forms of "for" that seem appealing:
Allow slice-like syntax as shorthand for xrange():
for i in 10: # equivalent to "for i in xrange(10)"
for i in 5:10: # equivalent to "for i in xrange(5, 10)"
for i in 20:10:-1: # equivalent to "for i in xrange(20, 10, -1)"
Note that although the functionality is the same as using xrange, there is
no requirement the the implementation actually use xrange objects to provide
these loops over numeric ranges.
Make the "<variable> in" part optional:
for 10: # loops 10 times (the "10" is the xrange
shorthand suggested above)
for alist: # loops as many times as there are elements
Empty "for" loops indefinitely (equivalent to the beloved "while 1"):
<code that eventually breaks or raises>
A subthought: Slice notation as shorthand for xrange() need not be
restricted to "for" statements. (I've never really cared for the name
"xrange" for the functionality it provides, anyway. I'd be happy to see an
String method to remove trailing newline
Since readline() and its relatives return strings with '\n' attached
(sometimes), it would be convenient to have a built-in string method that
removes one if it exists (seems like I'm often coding little functions to do
<string>.chomp() # sorry, borrowed the method name from Perl
Then, combined with above suggestions:
while line := f.readline();
This method is not much different from <string>.rstrip(), except that it
leaves other trailing spaces intact.
More information about the Python-list