6

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

1
  • on a side note relying on this kind of stuff in production code is usually a bad idea Commented Aug 28, 2012 at 4:55

2 Answers 2

17
import inspect inspect.getfile(fn) 

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

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

return "filename: " + fn.func_code.co_filename 

2 Comments

It's important to note that this is relying on implementation details and may not work outside of CPython. Using inspect is the actual correct answer, but why go for correct when the one-liner is easier, right? :|
@Matthew Trevor Correct, The inspect is better, I didn't know about this and learned it from gnibbler's answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.