Find which function is using a given class in python

I have class

class A:
 def __init__(self):
  print(i was used by :)

# if i call this class from the function below,
 
def my_func():
 a = A()

# I need class A to print that "i was used in: my_func() "

Is there any solution for this ?

Answer

If you know the function name:

You could try something like:

class A:
    def __init__(self, func):
        print('i was used by:', func.__name__)

def my_func(func):
    a = A(func)
my_func(my_func)

Output:

i was used by: my_func

This you would specify the function instance, which is the most optimal way here, then just use the __name__ to get the name of the function.

If you don’t know the function name:

You could try the inspect module:

import inspect
class A:
    def __init__(self):
       print('i was used by:', inspect.currentframe().f_back.f_code.co_name)

def my_func():
    a = A()
my_func()

Or try this:

import inspect
class A:
    def __init__(self):
        cur = inspect.currentframe()
        a = inspect.getouterframes(cur, 2)[1][3]
        print('i was used by:', a)

def my_func():
    a = A()
my_func()

Both output:

i was used by: my_func