Hashable object with self references OR how to create a tuple that refers to itself

Prasad, Ramit ramit.prasad at jpmorgan.com
Fri Jun 15 16:23:50 EDT 2012


> > I am trying to create a collection of hashable objects, where each
> > object contains references to
> > other objects in the collection.  The references may be circular.
> >
> > To simplify, one can define
> >     x= list()
> >     x.append(x)
> > which satisfies x == [x].
> > Can I create a similar object for tuples which satisfies x == (x,)?
> 
> You can create a tuple in "C" and then put a reference to itself into it,
> but I am quite convinced that you cannot do it in Python itself.
> (Of course, you could use "cython" to generate C code with a source
> language
> very similar to Python).
> 
> But, you do not need tuples; You could use a standard class:
> 
> >>> class C(object): pass
> ...
> >>> c=C()
> >>> c.c=c
> >>> d=dict(c=c)
> >>> d
> {'c': <__main__.C object at 0xb737f86c>}
>

Using a class is a good approach. You can also override __contains__ 
for the custom classes internal collection so instead of x==[x,] you 
would use x in obj where obj is a collection with the equivalent [x,].

Not entirely sure why Dieter is bringing up C code / Cython... 

Just as a note, if you store references to an object A in the collection
in another object B in the collection and then try to remove A from the
collection it will not get garbage collected nor removed from B. To
allow for garbage collection you should store a weakref instead.
http://docs.python.org/library/weakref.html 

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  



More information about the Python-list mailing list