Home > python > Determine the name of the current function

Determine the name of the current function

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.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: