I want to get the original file/scriptname, etc of the function that is being decorated. How can I do that?
def decorate(fn):
def wrapped():
return "scriptname: " + fn.scriptname?
return wrapped
I tried using fn.__code__
but that gave me more stuff that I needed. I could parse that string to get the function name, but was wondering if there is a more elegant way to do it
A decorator in Python is a function that takes another function as its argument, and returns yet another function . Decorators can be extremely useful as they allow the extension of an existing function, without any modification to the original function source code.
Decorators accept a function and return a function This function accept a number and returns either True or False depending on whether that number is prime or not.
You can create a decorator that can print the details of any function you want. To do this the functions in Python certain attributes. One such attribute is __code__ that returns the called function bytecode. The __code__ attributes also have certain attributes that will help us in performing our tasks.
Decorators use a special syntax in JavaScript, whereby they are prefixed with an @ symbol and placed immediately before the code being decorated.
import inspect
inspect.getfile(fn)
This won't work for builtin functions though, you have to fall back to inspect.getmodule
for those.
Try this:
return "filename: " + fn.func_code.co_filename
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With