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:

 

[crayon]
import inspect

fn_name = inspect.stack()[0][3]
[/crayon]

 

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

 

[crayon]
import inspect

fn_name = inspect.stack()[1][3]
[/crayon]

 

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

[crayon]
import inspect

def get_current_function():
return inspect.stack()[1][3]
[/crayon]

 

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.