[Python-Dev] For Python 3k, drop default/implicit hash, and comparison

Nick Coghlan ncoghlan at gmail.com
Sun Nov 27 03:09:37 CET 2005


Adam Olsen wrote:
> On 11/26/05, Noam Raphael <noamraph at gmail.com> wrote:
>> [...stuff about using Ref() for identity dictionaries...]
> 
> I too have thought along these lines, but I went one step further. 
> There is an existing function that could be modified to produce Ref
> objects: id().
> 
> Making id() into a type allows it force unsignedness, incorporate a
> method for easy printing, maintain a reference to the target so that
> "id(x.foo) == id(x.bar)" doesn't risk reusing the same id.. and the id
> object would be the same size as an int object is today.  I don't see
> any disadvantage, except perhaps code that assumes id() returns an
> int.  That could be fixed by having id() subclass int for a few
> versions while we transition, although that may require we store the
> pointer seperate from the integer value.
> 
> id() would be usable in dicts as a value, behaving as Noam suggests
> that Ref behave.  Kills two birds with one stone.

I've occasionally considered the concept of a "Ref" class - usually when I 
want to be able to access a value in multiple places, and have them all track 
rebinding operations. You can't do it perfectly (you need to rebind the 
attribute directly because objects aren't notified of name rebinding) but you 
can get pretty close (because objects *are* notified of augmented assignment).

However, re-using id() for this doesn't seem like the right approach.

Cheers,
Nick.

P.S. Yes, those musings where prompted at least in part by Paul Graham's 
ramblings ;) The sample version below obviously misses out all the slots it 
would actually need to delegate to get correct behaviour.

Py> class Ref(object):
...     def __init__(self, val):
...         self._val = val
...     def __str__(self):
...         return str(self._val)
...     def __repr__(self):
...         return "%s(%s)" % (type(self).__name__, repr(self._val))
...     def __iadd__(self, other):
...         self._val += other
...         return self
...
Py> n = Ref(1)
Py> i = n
Py> n += 2
Py> n
Ref(3)
Py> i
Ref(3)
Py> def make_accum(n):
...     def accum(i, n=Ref(n)):
...         n += i
...         return n._val
...     return accum
...
Py> acc = make_accum(3)
Py> acc(1)
4
Py> acc(5)
9


-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-Dev mailing list