Function docstring as a local variable

Roy Smith roy at panix.com
Mon Jul 11 00:41:51 CEST 2011


In article <mailman.852.1310336017.1164.python-list at python.org>,
 python at bdurham.com wrote:

> I'm not sure how a function can get a generic handle to itself, but if
> you're willing to hardcode the function name, then this technique works:
> 
> def test():
>     """This is my doc string"""
>     print test.__doc__
> 
> test()
> 
> Outputs:
> 
> This is my doc string
> 
> Malcolm

I'm sure there has to be a cleaner way that this, but one possible way 
for a function to find its name is to catch an exception and look at the 
traceback:

---------------------------------------
#!/usr/bin/env python                                                                               

import sys
import traceback

def foo():
    "The Larch"
    try:
        raise Exception
    except Exception, ex:
        _, _, tb = sys.exc_info()
        stacks = traceback.extract_tb(tb)
        file_name, line_number, function_name, text = stacks[0]
        print "I am %s", function_name
        print "My docstring is", eval(function_name).__doc__

foo()
--------------------------------------

This works, but yuck.



More information about the Python-list mailing list