views:

54

answers:

1

Suppose I have a free function which has been called from a class method. Is there a way for me to introspect the call stack in the free function and determine what object called me?

def foo(arg1) :
  s = ? #Introspect call stack and determine what object called me
  # Do something with s

Thanks!

+2  A: 

There isn't really the concept of "a calling object". You can introspect the stack and find if your calling function has a first argument named self, I guess -- if you're called directly from a normally-coded instance method (absolutely not a class method as you say... I imagine you're just horribly mis-speaking, because the very purpose of a classmethod is to not have "an object", i.e. an instance, involved!-), that should detect that.

The inspect module offers you the tools for advanced introspection (recommended only for debugging and development purposes, never for "actual production use"!!!). However, note that even tracing the function is not trivial: you get stack frames which point to the code object (which doesn't point back to the function).

Still, it can be arranged, because there are pseudo-dicts of local variables also pointed from stack frames, and arguments are local variables, so what you're looking for is an entry in the local variables of your caller's stack frame that is named self (and in addition of course you need a lot of optimism and a smidgeon of luck as nobody forces your caller to be coded sensibly -- the argument normally named self could be named otherwise, and then you're in trouble;-).

Alex Martelli
a good point regarding the class method mentioned, even other languages include this nomenclature for methods that aren't bound to an instance
Matt Joiner
@Matt, yep, I believe we borrowed the name (and concept) from Smalltalk in particular.
Alex Martelli