Scope rule pecularities

Josiah Carlson jcarlson at uci.edu
Sun May 9 04:31:42 EDT 2004


>>Except when the /referenced object/ is immutable.  Name rebinding is 
>>necessary to reference the newly created immutable object that was 
>>created through the +=, -=, /=, %=, *=, &=, |=, or ^= operations.
> 
> 
> IMO having operators that should work in place for object that
> are immutable, sound contradictory. Having the following code:
> 
>   a = ...
>   b = ...
>   c = a
>   a += b
> 
> I now expect a and c still to be the same object.

If 'a' is mutable, and 'a' has the proper __iadd__ operator, then 'a' 
and 'c' will be the same object when you are done.  However, integers, 
strings, floats,... are immutable, so 'a' and 'c' won't be the same 
object in those cases (Python only rebinds objects that are specified, 
due to the whole "explicit is better than implicit" Zen).

The real thing to remember is that Python isn't <insert the language you 
expect Python to behave like>, and your expectations are not what 
actually happens.  What you think /should/ happen is not what /does/ 
happen, and I am quite sure it is not what /Guido thinks should happen/.

Once you wrap your mind around the implications of mutables and 
immutables, and what you can/can't do with them, then perhaps the += 
semantics will seem less confusing.

  - Josiah



More information about the Python-list mailing list