0

When you pass a defined function as a callback or event/handler function, say to a thread or multiprocess object, can you get the actual name of the function in executed function?

For example, if I pass Test, (i.e. def Test()) to some Python object that needs such a callback during initialization, can I get the name of the function to print before I invoke it? Name from the passed object itself. I tried using __str__ and __repr__, but both return a full descriptor of the pass (function) object... '<function OnProcess..Test at 0xb33f9390>'. I could just parse the string removing '<function', '', and at '0xb33f9390>' elements of string representation of the passed (function) object, ending up with 'OnProcess.Test'. But is there a better way? More elegant way to get just the function name? Can't use inspect module because I have not called the function as yet, so no stack frame, it is just a parameter value at the point I want to get the name.

Ken White
  • 123,280
  • 14
  • 225
  • 444
Schorschi
  • 95
  • 2
  • 8
  • 3
    Does this answer your question? [How to get a function name as a string?](https://stackoverflow.com/questions/251464/how-to-get-a-function-name-as-a-string) – enzo Aug 14 '21 at 02:56
  • Keep in mind that there are callable objects other than functions - instances of a class with a `__call__()` method, for example. If you get too specific with your code to extract a name from the callable, you might needlessly disallow the user from passing such an alternative value. – jasonharper Aug 14 '21 at 03:18
  • @enzo, I don't believe so... since I am trying to get the name of an object that does not yet exist in any frame available, when I inspect the stack. The context of a method at the time I need the name, it is just an object reference, yet to be invoked. – Schorschi Aug 15 '21 at 01:29
  • @jasonharper, yes, true. However, my need is just for logging/execution trace logging. I wanted to use 'Process.Test' as more human understandable, readable, than for example. – Schorschi Aug 15 '21 at 01:32
  • @Schorschi You don't need to inspect the stack, that's only one of the 13 answers of the linked question. [This answer](https://stackoverflow.com/a/47155992/9997212) does what you want, so yes, it does answer your question. – enzo Aug 15 '21 at 01:53
  • @enzo, do you mind illustrating how? I realize everything is an object in python, so get that there has to a reference to the 'name' of the object in some place, no doubt, I just am not seeing it as yet. – Schorschi Aug 15 '21 at 02:05
  • In the same way you're calling `__str__` on the object, just call `__qualname__`. – enzo Aug 15 '21 at 02:06
  • 1
    Ah, nuts... I was way over thinking this. Thanks. – Schorschi Aug 15 '21 at 02:12
  • No problem, pal. I still love you. – enzo Aug 15 '21 at 02:28

0 Answers0