along the lines, hash and obj. id.
castironpi at gmail.com
castironpi at gmail.com
Mon Feb 25 20:55:18 EST 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
after.
class A:
def __init__( self, d ):
self.d= d
d= {}
a= A( d )
d= {}
is different than:
d= {}
a= A( d )
d.clear()
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