Reciprocal data structures

Chris Angelico rosuav at gmail.com
Mon Jun 19 02:02:45 EDT 2017


On Mon, Jun 19, 2017 at 3:54 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> With a list? No, I would say it's a bad idea.
>
>
> Why a bad idea?
>
> As opposed to "can't be done", or "too hard and slow".

Maintaining a record of list indices inside an object, with the
specific proviso that:

> If the list is changed, the list updates the indices.

? I think it's a bad idea because it's trying to use a changeable
position as an attribute of an object. It seems like a job that's much
better done with an immutable identifier.

I might do it as the OP suggested *if* the IDs are never reused or
deleted (or if you delete by replacing the object with None or
something), which would make indices effectively immutable. But the
idea that you should have list mutations that have to go and update
everything else? Perilous. You're opening yourself up for a ton of
tiny bugs. Of course, if the OP is a perfect programmer who never
makes a single mistake, then sure, go ahead - it's not impossible -
but I don't like the idea that you can do a mutation that works, but
leaves things in a subtly inconsistent state, so the next operation
(looking up an object) also works, but the one *after that* doesn't.
It also means that you can't snapshot an ID to use as a reference, but
can only use them *right now* (eg in a method on that object), which
limits their usability.

ChrisA



More information about the Python-list mailing list