Parent references: hot or not?

Dylan Reinhardt python at dylanreinhardt.com
Sat Apr 19 16:53:01 CEST 2003


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.
2. Holding a reference to a parent isn't some kind of recursive paradox.
3. As I add Items, Container size will grow linearly, not exponentially
4. It will be impossible to fully delete a non-empty Container.

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.

Thanks in advance,

Dylan






More information about the Python-list mailing list