-1

I was wondering if maybe we could figure out which functions call another specific function?

For example,

def f1(): print 1 

def f2(): f1()

When we execute this script

>>> f2()
1

We should know f2 call my target f1. Is that possible?

Lamcee
  • 19
  • 4
  • You can pass in the invoker function as an argument to the function. Something like: def f2(f2) – Azeem Ghumman Feb 10 '17 at 08:11
  • Why do you need to know this? If the function needs to behave differently, there should be a parameter that tells it what to do, it shouldn't figure it out from which function called it. – Barmar Feb 10 '17 at 08:12
  • try this thread: http://stackoverflow.com/questions/2529859/get-parent-function Hopefuly it will be helpful! – Felbab Vukasin Feb 10 '17 at 08:14
  • Possible duplicate of [Getting the caller function name inside another function in Python?](http://stackoverflow.com/questions/900392/getting-the-caller-function-name-inside-another-function-in-python) – Paul Rooney Feb 10 '17 at 08:14
  • http://stackoverflow.com/a/1349359/5417164 – joydeep bhattacharjee Feb 10 '17 at 08:18

3 Answers3

0

inspect.getframeinfo and other related functions in inspect can help:

>>> import inspect
>>> def f1(): f2()
... 
>>> def f2():
...   curframe = inspect.currentframe()
...   calframe = inspect.getouterframes(curframe, 2)
...   print 'caller name:', calframe[1][3]
... 
>>> f1()
caller name: f1
>>> 
PinkFluffyUnicorn
  • 1,260
  • 11
  • 20
0

What I think you want to do is to do a stack trace. This is possible by calling

traceback.print_exc()

Where you of course need to import traceback.

bremen_matt
  • 6,902
  • 7
  • 42
  • 90
0

You can use module traceback

def f():
    pass
    import traceback
    traceback.print_stack()
    print "Still working just fine"
    pass

def caller():
    f()

caller()

yields

  File "traceback.py", line 12, in <module>
    caller()
  File "traceback.py", line 9, in caller
    f()
  File "traceback.py", line 4, in f
    traceback.print_stack()
makarchuk@makarchuk:~/Workspace$ python2 traceback.py 
  File "traceback.py", line 13, in <module>
    caller()
  File "traceback.py", line 10, in caller
    f()
  File "traceback.py", line 4, in f
    traceback.print_stack()
Still working just fine
Darth Kotik
  • 2,261
  • 1
  • 20
  • 29