ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Determining Current Function Name
Submitter: Alex Martelli (other recipes)
Last Updated: 2001/07/17
Version no: 1.0
Category:

 

4 stars 8 vote(s)


Approved

Description:

You want to determine the name of the currently running function, e.g. to create error messages that don't need to be changed when copied to other functions. Function _getframe of module sys does this and much more.

Source: Text Source

# use sys._getframe() -- it returns a frame object, whose attribute
# f_code is a code object, whose attribute co_name is the name:
import sys
this_function_name = sys._getframe().f_code.co_name

# the frame and code objects also offer other useful information:
this_line_number = sys._getframe().f_lineno
this_filename = sys._getframe().f_code.co_filename

# 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:
def whoami():
    import sys
    return sys._getframe(1).f_code.co_name

me  = whoami()

# this uses argument 1, because the call to whoami is now frame 0.
# and similarly:
def callersname():
    import sys
    return sys._getframe(2).f_code.co_name

him = callersname()

Discussion:

Inspired by Recipe 10.4 in O'Reilly's Perl Cookbook. Python's sys._getframe(), new in 2.1, offers information equivalent to Perl's builtin caller(), __LINE__ and __FILE__. If you need this for older Python releases, see recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52315, "Obtaining the name of a function/method".



Add comment

No comments.



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. Treat the Win32 Registry ...

4. Watching a directory ...

5. Union Find data structure

6. Function Decorators by ...

7. MS SQL Server log monitor

8. Table objects with ...

9. wx twisted support using ...

10. More accurate sum




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.