0

Let's say for example I have this fuction:

def example(foo:str="bar"):
  # code

How do I get the name of the function (for this, "example") that executed the code, something like this:

def example(foor:str="bar"):
  print(functions.get()["name"]) # prints "example"

I looked at the inspect modules and the examples but they didn't make sense and didn't seem to do what I wanted.

Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
vlone
  • 33
  • 7
  • This seems to be a duplicate: https://stackoverflow.com/questions/2654113/how-to-get-the-callers-method-name-in-the-called-method – Cpt.Hook Dec 01 '22 at 15:26
  • 2
    `inspect.currentframe().f_code.co_name`? – Mechanic Pig Dec 01 '22 at 15:26
  • Does this answer your question? [How to get the caller's method name in the called method?](https://stackoverflow.com/questions/2654113/how-to-get-the-callers-method-name-in-the-called-method) – Morten Jensen Dec 01 '22 at 15:27
  • @MechanicPig `inspect.currentframe().f_code.co_name` worked for me! thank you – vlone Dec 01 '22 at 15:42

1 Answers1

0

Did you mean something like this:

def example():
    pass

a = []
a.append(example)

# What is a[0]'s name?
print(a[0].__name__)

As en element of the list a, we don't know the function's name. But by calling the __name__ attribute, I get the associated string.

scr
  • 853
  • 1
  • 2
  • 14