along the lines, hash and obj. id.

castironpi at castironpi at
Tue Feb 26 02:55:18 CET 2008

I'd like to do this:

a= list( range( 5 ) )
assert a== [ 0, 1, 2, 3, 4 ]
for i in ref( a ):
    i.ref*= 2
a= deref( a )
assert a== [ 0, 2, 4, 6, 8 ]

In the for loop, i objects maintain their identities, while still
being reassigned.  The first way I think of is this:

class Ref:
    def __init__( self, ref ):
        self.ref= ref
    def __repr__( self ):
        return '<Ref %r>'% self.ref

def ref( it ):
    for i, e in enumerate( it ):
        it[i]= Ref(e)
    return it

def deref( it ):
    return [ i.ref for i in it ]

Dictionaries, sets, and the primitives all have ways to do this, in
particular, to reset them: a= {} is equivalent to a.clear(), except
that other references to it corefer before, and in the former, don't

class A:
    def __init__( self, d ):
        self.d= d

d= {}
a= A( d )
d= {}

is different than:

d= {}
a= A( d )

a.d still refers to d in the second, whereas the identity is broken in
the first.

Can perhaps a subclass of List return references to its elements, so
that L[2] is L[2], even if you assign it to a different value later,
and even in the case of integers.?

(*This came out a little funny.)

More information about the Python-list mailing list