Some Guy
Some Guy

Reputation: 722

Assign function to variable and get variable name from inside said function

def my_function():
   ... 

my_variable = my_function
my_variable()

In this case, is there a way to get my_variable as string from inside my_function?

Upvotes: 0

Views: 50

Answers (1)

alec_djinn
alec_djinn

Reputation: 10799

You could look into globals() for instances of the function.

def my_func():
    names = [k for k,v in globals().items() if str(v).startswith("<function my_func ")]
    print(names[1:]) #names[0] is "my_func"

my_var = my_func
my_var() #['my_var']

asd = my_func
asd() #['my_var', 'asd']

Upvotes: 1

Related Questions