Archive

Posts Tagged ‘function’s name’

Determine the name of the current function

October 24, 2012 Leave a comment

Problem
You want to determine the name of the current function.

Solution

import sys

def whoami():
    print '# this function is:', sys._getframe().f_code.co_name
    print '# this line number is:', sys._getframe().f_lineno
    print '# this file\'s name is:', sys._getframe().f_code.co_filename

whoami()

Output:

# this function is: whoami
# this line number is: 5
# this file's name is: na.py

Also, by calling sys._getframe(1), you can get this information for the *caller* of the current function. So you can package this functionality up into your own handy functions:

import sys

def get_function_name():
    return sys._getframe(1).f_code.co_name

def whoami():
    func_name = get_function_name()
    print '# current function\'s name:', func_name

whoami()

Output:

# current function's name: whoami

This tip is from here.