Inspect function caller

You write a function func() and coorperate with popular package in the way this package subscribe func(). You are curious which function of this package actually call your func. inspect could help you.

# This part happen in popular package.
def caller():
  a = 1
  b = a + 1
  func() # This function could be called implicitly.
  c = b + 1
  d = c + 1
# This is your own function.
import inspect
def func():
  # f_back go up one in the stack
  print(inspect.getsource(inspect.currentframe().f_back))
  # Other part...

When you try this popular package methods.

>>> caller()

Output:

def caller():
  a = 1
  b = a + 1
  func()
  c = b + 1
  d = c + 1

package

I wrote a package called ambush to do this. https://github.com/ke-zhang-rd/ambush

Example:

main.py
 1from sub import Member
 2
 3
 4class Primary:
 5
 6    def foo(self):
 7        a = 1
 8        a = a + 1
 9        m = Member()
10        m.bar()
11        a = a + 1
12        a = a + 1
13
14
15p = Primary()
16p.foo()
sub.py
1class Member:
2
3
4    def bar(self):
5        from ambush import detector
6        detector()

Output:

Who is calling current function
=========================================================
In file:
/Users/kz2249/tmp/main.py

class Primary:
    # by caller function:
    def foo in line 6
        ...
        # actually call:
        m.bar() # in line 10
        ...

Peek:
---------------------------------------------------------
    def foo(self):
        a = 1
        a = a + 1
        m = Member()
        m.bar()
        a = a + 1
        a = a + 1

=========================================================