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 ?

5
  • 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. Commented Aug 31, 2021 at 4:19
  • 1
    I mean, maybe by using various stack introspection hacks. Almost certainly, you should just require the function be provided as an argument. Commented Aug 31, 2021 at 4: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. Commented Aug 31, 2021 at 4:23
  • 1
    check this: stackoverflow.com/questions/2654113/… Commented Aug 31, 2021 at 4:28
  • 1
    check this: stackoverflow.com/a/900404/10217732 Commented Aug 31, 2021 at 4:39

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks but still, I have no idea which function is calling my class, I got a huge chunk of Django code in which i need to figure out from where an API request is fired. There is a class for handling that, but i have no idea from where it is used.
@cod4 Edited my answer, check the Edit: part, that would work
yea, that's exactly what i was looking for !
@cod4 Your welcome, added an even shorter version, feel free to check it out :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.