PEP 276 -- What else could iter(5) mean?
Huaiyu Zhu
huaiyu at gauss.almadan.ibm.com
Mon Mar 4 23:05:19 EST 2002
On Sun, 03 Mar 2002 20:04:44 GMT, logistix <logstx at bellatlantic.net> wrote:
[ example using the proposed 'for i in n' syntax ]
>
>When you run the script, a user is prompted for some numbers. If they enter
>1,2,3,4,5, a tuple of (1,2,3,4,5) is created that can then be iterated. If
>they just enter 5, then they probably only want to perform this operation on
>5, but when functionInMyModule() is called, the results will be identical to
>the first example, when you really want it to throw an error or create a
>tuple of (5).
This is indeed one of the best counter examples for this proposal.
I do not think that there is any conceptual difficulty to explain that
for i in n ==> for i in iter(n)
iter(3) ==> xrange(3)
which is all that is in the proposal. This is elegant and easily
explainable even to a newbie. I actually like this quite a lot.
However, I still think the potential for unintended effects (bugs) is too
big when a one-element sequence behaves substantially different from the
element itself. Imagine if Python had a character type and that
"abc" == ['a', 'b', 'c'] == 'd' != "d"
Even though it can be explained, what utter confusion it would result in
actual use!
Here's another example of a similar nature. In Matlab there is a fuction
sum(x) that would return sum of elements of x, if x is a (row or column)
vector, or a row vector of columnwise sums of x, if x is a matrix. This is
very handy when used in isolation, but a pain in programs, because the
behavior on (1xm) matrix has a different semantics. Suppose x is a (5x4)
matrix. Then (using Python syntax instead of Matlab's)
sum(a[0:n:, :])
would give a (nx4) matrix for n in 5, 4, 3, 2, but for n==1, it gives a
scalar which is the sum of x as a row vector.
It is very expensive to guard against such "discontinuity of semantics" that
the cost completely overweigh the benefit.
Huaiyu
More information about the Python-list
mailing list