|
Original |
Translation |
|
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.
|
|
|
43
|
There's an alternative way of spelling this that seems attractive but is generally less robust than the "while True" solution::
|
|
|
44
|
line = f.readline() while line: ... # do something with line... line = f.readline()
|
|
|
45
|
|
46
|
The best approach is to use iterators, making it possible to loop through objects using the ``for`` statement. For example, in the current version of Python file objects support the iterator protocol, so you can now write simply::
|
|
|
47
|
for line in f: ... # do something with line...
|
|
|
48
|
Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?
|
|
|
49
|
The major reason is history. Functions were used for those operations that were generic for a group of types and which were intended to work even for objects that didn't have methods at all (e.g. tuples). It is also convenient to have a function that can readily be applied to an amorphous collection of objects when you use the functional features of Python (``map()``, ``apply()`` et al).
|
|
|
50
|
In fact, implementing ``len()``, ``max()``, ``min()`` as a built-in function is actually less code than implementing them as methods for each type. One can quibble about individual cases but it's a part of Python, and it's too late to make such fundamental changes now. The functions have to remain to avoid massive code breakage.
|
|