Automatically find the source of a method invocation?

holger krekel pyth at devel.trillke.net
Fri Aug 30 15:46:02 EDT 2002


Robb Shecter wrote:
> Hi,
> 
> 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)

Why is this a problem? 

If you really want to be implicit <wink> then you might do something like:

import inspect
probable_calling_instance = inspect.currentframe(-1).f_locals['self']

which assumes 
- the caller comes directly from a bound instance method
- 'self' is really the name where the instance object is bound to


Another possibility is that the sender gets his
own channel while registering.  

    # while initializing
    self.channel = service.register_sender(self)

    # later
    self.channel.sendMessage(msg)

It depends on what you really want to do. I wouldn't bother too much ...

    holger




More information about the Python-list mailing list