2

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 ?

  • Better yet put that print inside `my_func` as `print("my_func willl now be calling A")`. Or, just pass the function name to the constructor of A as `A("my_func")` and use it. – Niel Godfrey Pablo Ponciano Aug 31 '21 at 04:19
  • 1
    I mean, maybe by using various stack introspection hacks. Almost certainly, you should just require the function be provided as an argument. – juanpa.arrivillaga Aug 31 '21 at 04:20
  • @NielGodfreyPonciano I have no idea which function is calling my class. I need to figure out which functions does. Somewhere in my code a class is used by a function which I'm not able to find. – Jeesson Johney Aug 31 '21 at 04:23
  • 1
    check this: https://stackoverflow.com/questions/2654113/how-to-get-the-callers-method-name-in-the-called-method – xiaowl Aug 31 '21 at 04:28
  • 1
    check this: https://stackoverflow.com/a/900404/10217732 – Suyog Shimpi Aug 31 '21 at 04:39

1 Answers1

6

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
U13-Forward
  • 69,221
  • 14
  • 89
  • 114