Question

I found same similar question, but my question is diffent

def trace ():
   ?

class A():
  @staticmethod
  def Aha():
     trace ()
     ...

I want the trace output

A.Aha() was called

I have known how to get function name through inspection, and get class name of instance.method, such this:

self_argument = frame.f_code.co_varnames[0]  # This *should* be 'self'.
instance = frame.f_locals[self_argument]
class_name = instance.__class__.__name__

but class static method have not self argument, what should I do ?

Was it helpful?

Solution

That is the very definition of a static method: it is called without a class argument (as in class methods) and without an instance argument (as in instance methods). The only real difference between a function declared in module scope and a static method is that the method name is defined in the class' namespace and not in the module's namespace.

In other words, you can't get to the class object directly. You can get the function name by examining the stack (although I am not sure how useful it is):

>>> import sys
>>> import traceback
>>> class A(object):
        @staticmethod
        def a():
            trace()
>>> def trace():
        print traceback.extract_stack(sys._getframe())[-3][3]
>>> A.a()
A.a()

And given the name, you could get to the class object by extracting from the name and looking it up in the module's namespace...

For reference:

frame @ -1 : call to traceback.extract_stack()
frame @ -2 : call to trace()
frame @ -3 : call to A.a()

OTHER TIPS

You can try to create a wrapper/decorator for Aha. I suggest you to read this and this if you don't know that decorators are.

Something like the following should print out the function name and then call the function.

def wrapper(func):
    def inner(*args, **kwargs):
        print("function {0} has been called".format(func.__name__))
        return func(*args, **kwargs)
    return inner

@wrapper
def f():
   print "I'm in the function

returns

In [16]: f()
function f has been called
in the function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top