|
Original |
Translation |
|
33
|
Why can't I use an assignment in an expression?
|
|
|
34
|
Many people used to C or Perl complain that they want to use this C idiom:
|
|
|
35
|
while (line = readline(f)) { // do something with line }
|
|
|
36
|
where in Python you're forced to write this::
|
|
|
37
|
while True: line = f.readline() if not line: break ... # do something with line
|
|
|
38
|
|
39
|
if (x = 0) { // error handling } else { // code that only works for nonzero x }
|
|
|
40
|
The error is a simple typo: ``x = 0``, which assigns 0 to the variable ``x``, was written while the comparison ``x == 0`` is certainly what was intended.
|
|
|
41
|
Many alternatives have been proposed. Most are hacks that save some typing but use arbitrary or cryptic syntax or keywords, and fail the simple criterion for language change proposals: it should intuitively suggest the proper meaning to a human reader who has not yet been introduced to the construct.
|
|
|
42
|
An interesting phenomenon is that most experienced Python programmers recognize the ``while True`` idiom and don't seem to be missing the assignment in expression construct much; it's only newcomers who express a strong desire to add this to the language.
|
|