Python – Get Name of Current Function

Q: How do I get the name of the current python function, I want to output its name as part of some logging information.

 

A: Just import the ‘inspect’ module and call its stack() method to get access to the call stack, for example, to get the name of the current function:

 

 

The first index indicates the stack position, so to get the name of the parent calling function use:

 

 

or to define a function that returns the name of the function from which it was called:

 

Introspection is one of the really cool features of modern software programming languages!

2 replies
  1. m4z
    m4z says:

    I just noticed this while testing your code snippet: Your numbering is off-by-one, so the current function is at index [0][3], the parent at [1][3], etc. Nevertheless, thanks for the useful example!

Comments are closed.