Scope rule pecularities

Antoon Pardon apardon at forel.vub.ac.be
Thu May 13 06:41:45 EDT 2004


Op 2004-05-13, Andrew Bennetts schreef <andrew-pythonlist at puzzling.org>:
> On Thu, May 13, 2004 at 07:40:45AM +0000, Antoon Pardon wrote:
>> 
>> But I don't ask for rebinding, I ask for easy in place copying.
>> 
>> Lets name a new operator "@=" Now given variables A and C
>> of the same class I would like to see the following:
>> 
>> >>> B = A
>> >>> A @= C
>> >>> A is B
>> True
>> >>> A is C
>> False
>> >>> A == C
>> True
>
> It's already easy:
>
>     from copy import copy
>
>     b = a
>     a = copy(c)

Sorry, you are wrong.  After this you get

>>> a is b
False


> [I'm using lowercase variables for instances, which is the usual
> convention... uppercase suggests that it's a class name (or maybe a
> constant) to me.]
>
> No new syntax necessary.

>> And maybe if D is of an other class
>> 
>> >>> D @= C
>> TypError
>
> Assignments in Python don't care about what the name is currently bound to,
> if anything.

This is not assignment (as is understood in python).

> They just (re)bind the name to an object -- so having an
> assignment to D depend on the type of D's old value would be inconsistent
> with the rest of Python.
>
> Many classes support a convention where you can pass a single argument to
> their constructor to construct a copy, e.g.:
>
>     l2 = list(l1)
>
> So your example could become:
>
>     d = d.__class__(c)

No to get the same effect as what I want you need something like this:

class M:

  def cp_from(self, a):
    for key in dir(self):
      value = getattr(a,key)
      setattr(self,key,value)

d.cp_from(c)

-- 
Antoon Pardon



More information about the Python-list mailing list