How can I get the file name of the function that is passed to my decorator in python?

StackOverflow https://stackoverflow.com/questions/12152911

سؤال

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

هل كانت مفيدة؟

المحلول

Try this:

return "filename: " + fn.func_code.co_filename

نصائح أخرى

import inspect
inspect.getfile(fn)

This won't work for builtin functions though, you have to fall back to inspect.getmodule for those.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top