Parent references: hot or not?

Jp Calderone exarkun at intarweb.us
Sat Apr 19 10:57:56 EDT 2003


On Sat, Apr 19, 2003 at 07:53:01AM -0700, Dylan Reinhardt wrote:
> Hi all,
> 
> I'm working on a project where I have multiple instances of a container
> class that each hold a large number of another class.
> 
> I need the "contained" object to be able to make use of methods and
> attributes in its container. Inheritance won't do the trick since the
> things I need to refer to will be pretty dynamic.
> 
> A very minimal example of what I'm doing:
> 
> ---------------
> 
> class Container:
>    def __init__(self):
>       self.items = {}
> 
>    def add_item(self, item_name):
>       self.items[item_name] = Item(self)
> 
>    some_attr = 'spam'
> 
> 
> class Item:
>    def __init__(self, parent):
>       self.parent = parent
> 
>    def some_method(self):
>       return self.parent.some_attr
> 
> ---------------
> 
> This seems to be working well, but I want to check my assumptions.
> 
> If I'm understanding correctly:
> 
> 1. Any Item's self.parent is only a *reference* to its parent.

  Currect.  All variables in Python are but references.

> 2. Holding a reference to a parent isn't some kind of recursive paradox.

  Correct - so long as you don't implement __del__ on either the container
or the item.  If you do, Python will be unable to free the cycle and it will
end up in gc.garbage.  Not that this will stop your program from running
but: 1) it will be a memory leak; 2) the code in your __del__ method won't
actually be run.

> 3. As I add Items, Container size will grow linearly, not exponentially

  Correct.

> 4. It will be impossible to fully delete a non-empty Container.

  I'm not sure what "fully delete" means here.  The container will certainly
be able to do "del self.items".  If "self.items" was the only reference to
the items in the container, then the will all be collected by Python and
de-allocated.

> 
> I think those are valid assumptions, but would appreciate any
> confirmation, contradiction, or insight anyone cares to offer.
> 
> Also, if there's some other consideration or reason why holding a
> reference to one's parent is a Bad Idea, I'd love to hear about it.

  Not really.  Someone else recently asked this, and I think one of the good
answers was that it's only a bad idea if it is possible to accomplish the
same thing without the reference without undue additional algorithmic
complexity.

  Jp

-- 
It is practically impossible to teach good programming style to
students that have had prior exposure to BASIC: as potential
programmers they are mentally mutilated beyond hope of
regeneration.        -- Dijkstra
-- 
 up 30 days, 11:02, 7 users, load average: 0.09, 0.19, 0.12





More information about the Python-list mailing list