[Python-il] [pyweb-il:1072] Python coding question

Shai Berger shai at platonix.com
Thu Jul 8 00:18:19 IDT 2010


On Wednesday 07 July 2010, Amit Aronovitch wrote:
> 
> I was not complaining about what it does.
> Only about the choice of symbol (too many people come from Java and C).
> Many questions on mailing lists are caused by this (Maybe <- or := would
> have been a little better).

"[p]racticality beats purity" (Tim Peters, "The Zen of Python"). Making the 
common thing (binding) use one character is IMHO a very good decision; it was 
good for C, and it is good for Python.

> Introducing += made the problem even worse. For example, too many people are
> trying to find magic-methods to overload 'the operator =', when in fact it
> has nothing to do with the object on the RHS (only manipulates the local
> namespace).

It is not people coming from C or Java (both of which lack operator 
overloading) who bring these issues up. And += is another one of those 
brilliant contributions of C, making the common case simpler and increasing 
readability. I wouldn't like the trade-off where you "win" a couple of 
questions on mailing-lists and pay for it with the DRY in 

complex_or_just_long_reference = complex_or_just_long_reference + 1
 
>  Some examples for common bugs caused by this (hebrew):
> http://tinyurl.com/38tt8hu
> 
Your explanation there is elegant, clear, well-written, and newbies reading it 
will be better off for it; but it is ultimately incorrect. Python does have 
true variables -- though you need to work a little harder to see them. 
Consider:

>>> def f():
...   funcs = []
...   for i in range(5):
...      def g():
...        return i
...      funcs.append(g)
...   return funcs
... 
>>> funcs = f()
>>> funcs[0]
<function g at 0xb75dd80c>
>>> funcs[1]
<function g at 0xb75dd17c>

We have created a list of functions, each supposedly defined over a different 
value of i. Each is a separate object, because in principle the closures are 
different. If i were really nothing but a name that gets re-bound in every 
loop iteration, we would expect, for any j in 0..4, to have funcs[j]()==j...

>>> funcs[1]()
4

...but in fact, they all return the last value; the closure references a 
variable, not a name.

Have fun,
	Shai.


More information about the Python-il mailing list