Scope rule pecularities

Andrew Bennetts andrew-pythonlist at puzzling.org
Thu May 13 04:32:58 EDT 2004


On Thu, May 13, 2004 at 07:58:07AM +0000, Antoon Pardon wrote:
> Op 2004-05-13, Greg Ewing schreef <greg at cosc.canterbury.ac.nz>:
[...]
> 
> > Besides, the semantics are as consistent as anything
> > else in Python, where the objects being operated on
> > get to determine the meaning of just about everything.
> 
> So? Would you argue that the devellopers could just
> as easily have implemented "a += b" as equivallent to
> "a = a - b" with half of the core classes and called that
> just as consistent as choosing it equivallent to
> "a = a + b" for all core classes because the objects
> being operated on get to determine the meaning?

Well, classes get to do whatever they think makes sense: in the end it's all
calls to methods of the object, whether via an actual method call
"obj.foo()" or by an operator "obj * 2" (which calls obj.__mul__(2)) or an
augmented assignment "obj += 'x'" (which calls obj.__iadd__('x')).  It's up
to the objects to make sense, not the Python language.

Even though Python chooses to have some immutable builtin types (like
ints and strings) for a variety of practical reasons, augmented assignment
does what people expect in all these cases:

    s = 'abc'
    s += 'd'

    i = 7
    i += 3

    l = [1, 2, 3]
    l += [4, 5, 6]

Augmented assignments are still assignments, and that makes perfect sense to
me -- each of those behave exactly like their obvious longer versions:

    s = 'abc'
    s = s + 'd'

    i = 7
    i = i + 3

    l = [1, 2, 3]
    l = l + [4, 5, 6]

(Yes, there are tricky examples that do behave differently -- but I try to
avoid tricky things, because they tend to be hard to read.  I almost only
find I want to use augmented assignment on integers and occasionally
strings.)

-Andrew.





More information about the Python-list mailing list