nested structure with "internal references"
pavlovevidence at gmail.com
Fri Sep 25 20:29:54 CEST 2009
On Sep 25, 10:11 am, Torsten Mohr <tm... at s.netic.de> wrote:
> sorry for posting in german before, that was a mistake.
> I'd like to use a nested structure in memory that consists
> of dict()s and list()s, list entries can be dict()s, other list()s,
> dict entries can be list()s or other dict()s.
> The lists and dicts can also contain int, float, string, ...
> But i'd also like to have something like a "reference" to another
> I'd like to refer to another entry and not copy that entry, i need to
> know later that this is a reference to another entry, i need to find
> also access that entry then.
> Is something like this possible in Python?
> The references only need to refer to entries in this structure.
> The lists may change at runtime (entries removed / added), so
> storing the index may not help.
Hmm, I think I understand what you're asking but I don't think there's
an easy way.
Probably the most straightforward way is to use "cells" of some sort
to contain the entries in a list or dict; then take references to the
cells. That way you can change the cell's value while still
maintaining the reference. For instance, suppose you have a list like
lst = [ 1, 2, 3, 4 ]
Convert it to this:
lst = [ , , ,  ]
where you are using a nested singleton list as the cell type. Then,
you can take a reference like this:
ref = lst
If you insert an item into the list, the reference remains valid:
And, if you change the value of the cell, the reference will see the
lst = 5
The downside is that you have to add  everywhere. The reference's
value is ref, not just ref. The third item in the list is lst
, not just lst. You could define custom list- and dict-like
classes that automatically do this, mitigating the problem somewhat.
I hope you could understand that suggestion, it's tough to describe.
Other than that, you are stuck with massive use of Observer pattern
(you'd have to create list- and dict-like types that know when
something is referencing them, and that notify the references whenever
More information about the Python-list