2

Currently I can get the function name using this command:

sys._getframe().f_code.co_name

I want to put it in of function like this:

def func_name:
    return sys._getframe().f_code.co_name

this function always returns 'func_name'. Is it possible to get the name the function which is calling this function?

2
  • traceback gives you the whole stack - docs.python.org/2/library/traceback.html so I presume you can get what you want from there Commented Aug 27, 2014 at 11:02
  • 2
    It's worth noting that while you can do this (see afeldspar's answer), 99% of the time when you think you want it (except for purposes like debugging a mess of threading code, or learning about how Python works by exploration), you really don't. Commented Aug 27, 2014 at 11:12

2 Answers 2

2

If the code you posted is working for you, then try giving _getframe() an argument of 1. The argument tells which frame to return, and it defaults to 0; you want 1, meaning the frame that frame 0 was called from.

However, the "inspect" module may be what you want, if you need it to work across more implementations of Python.

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

1 Comment

Also, if you already have the current frame and want its parent, you can always use f_back to walk up the stack.
1

Avoiding the use of sys._getframe:

import inspect

def bar():
    current_frame = inspect.currentframe()
    previous_frame = current_frame.f_back
    print previous_frame.f_code.co_name

def foo():
    bar()

foo()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.