object knows which object called it?

Duncan Booth duncan.booth at invalid.invalid
Mon Apr 6 19:09:55 CEST 2009

Reckoner <reckoner at gmail.com> wrote:

> hi,
> I have the following problem: I have two objects, say, A and B, which
> are both legitimate stand-alone objects with lives of their own.
> A contains B as a property, so I often do
> A.B.foo()
> the problem is that some functions inside of B actually need A
> (remember I said they were both standalone objects), so I have to
> often do:
> A.B.foo_func(A)
> Which is kind of awkward.
> Is there some way that B.foo_func() could somehow know that it was
> called as a property of A in this way?
> Note that I'm looking for the calling object and NOT the calling
> function.
You can do something like this if you really want (Zope does), but it is 
complex and confusing (Zope 3 has dropped implicit acquisition as being a 
bad idea). Have a look at 
which has the following example:

import ExtensionClass, Acquisition

class C(ExtensionClass.Base):

class A(Acquisition.Implicit):

  def report(self):
    print self.color


c.a.report() # prints 'red'


d.a.report() # prints 'green'

a.report() # raises an attribute error

and what you actually asked for: in the example above 'c.a.aq_parent is c'

If you want to confuse yourself you can install Zope's ExtensionClass and 
Acquisition modules from PyPi: 

More information about the Python-list mailing list