Automatically find the source of a method invocation?

Bengt Richter bokr at
Tue Sep 3 15:00:26 EDT 2002

On 30 Aug 2002 19:12:47 GMT, Robb Shecter <rs at> wrote:

>I'm making a small publish/subscribe module for an application, and I 
>want to have a reference to the source object that's sent a message.
>I was wondering if there was a way of determining it without the object 
>having to explicitly put a ref to itself in the method, ala:
>(What I want to avoid:)
>sendMessage(source=self, message=myMessage)
>Any ideas?
If an object had to get a connection object to participate (e.g., pso = PS(...) ),
then that instance would have a self. It wouldn't be the using object's self, but
would be 1:1 associated and might serve your purpose. If not, you could have the
connection object cache the using object's self. E.g.,

    class PS:
        def __init__(self, userself, *etc):
            self._userself = userself
            self.etc = etc
        def sendMessage(self, msg):
            # do whatever with self (PS instance)
            # and/or use self._userself as needed


    pso = PS(self, ...)

and then


really calls PS.sendMessage(pso, myMessage), and you can define sendMessage to do
with either self as you please.

You could also bind an alias like

    mySend = pso.sendMessage

and then write


noting that mySend is then a bound method and the pso instance will be passed implicitly
to PS.sendMessage.

Bengt Richter

More information about the Python-list mailing list