Scope rule pecularities

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


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)

[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.  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)

Although in practice it's hard to think of an example where I'd want to
dynamically care about the type of a object I'm about to discard like
that... I certainly can't think of a time when I've wanted to do that.

-Andrew.





More information about the Python-list mailing list