Best way to get the object parent


what is the best/better way to get an object parent?

I've found 2 ways:

  • obj.__parent__ (where is the code that set __parent__?)
  • getMultiAdapter((self.context, self.request), name=u'plone_context_state').parent(obj)


I use:

from Acquisition import aq_parent

parent = aq_parent(obj)

context_state does aq_parent(aq_inner(self.context)) to consider only containment but maybe using context is better.

There's also an issue in plone.api:

to get the parent(s).

1 Like

Acquisition implementation does this automatically for you:

(the above is the Python implementation; in practical reality, this is done in C; the few lines linked above don't do the actual resolution of special names Acquisition wrappers deal with, so some of the detail of how this is done is elided here, but one can follow/read this source well enough)

when you ask for __parent__ of acquisition-wrapped object, you get the thing the wrapper's _container attribute points at (the parent container), which is functionally equivalent to using Acqusition.aq_parent() (both one less import, and IMHO easier to read).


The iterate over all parents you can use for parent in obj.aq_chain