Reputation: 44315
Using a python decorator as follows
def decoratorFunctionWithArguments(msg):
def wrap(f):
def wrapped_f(*args, **kwargs):
print ...
return f(*args, **kwargs)
return wrapped_f
return wrap
I want to print out the following attributes of the function f
:
I probably need the inspect
module, but I am not quite sure how to use what method to achieve my goal. Or maybe I need to evaluate a traceback object?
Upvotes: 2
Views: 403
Reputation: 3186
This information can be retrieved in CPython with sys._getframe:
import sys
def mywrapper(msg):
def wrap(f):
def wrapped_f(*args, **kwargs):
f_back = sys._getframe().f_back
print f.__name__, f_back.f_code.co_filename, f_back.f_lineno
return f(*args, **kwargs)
return wrapped_f
return wrap
@mywrapper("message")
def f(x):
return x*x
f(3)
This will output the name of the function and the module and line number from where it is called.
Upvotes: 3