3

Consider the following pseudocode:

func1():
  func2() #func2 is called inside func1

My question is, in func2 can I access the name of the function it was called from? In this case, func1? Thanks!

TheoretiCAL
  • 19,461
  • 8
  • 43
  • 65
  • 1
    In 99% of cases there is no need to really do something like this. Variable *names* shouldn't alter your program in any way. I would urge you to look at your problem and see if there is any other alternative. – arshajii Jun 14 '13 at 00:24
  • 2
    I'm using a global error handling function to log errors, and want to retrieve the function which called the global error, hence I think this is proper for my needs. – TheoretiCAL Jun 14 '13 at 00:38

1 Answers1

11
import inspect

def func2():
    cframe = inspect.currentframe()
    func = inspect.getframeinfo(cframe.f_back).function
    print 'called from ' + func

def func1():
    func2()

func2()
func1()

Output:

called from <module>
called from func1
perreal
  • 94,503
  • 21
  • 155
  • 181