开发者

python introspection - how to detect the object i am in

Suppose I have a free function which has been called from a class method. Is there a way for me to introspect th开发者_Python百科e 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!


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;-).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜