access __doc__ from within function without reference to function name

Tim Chase python.list at tim.thechases.com
Tue Oct 2 16:45:04 CEST 2007


> The subject of this message might be a little cryptic, so here's an
> example of what I mean:
> 
> def foo():
>     """doc string of foo"""
>     print foo.__doc__
> 
>>>> foo()
> doc string of foo
> 
> What I want to know is whether it is possible to call __doc__ against
> some builtin method, like __func__ or something like that. So calling
> __doc__ without the functions name, something like this:
> 
> def foo():
>     """doc string of foo"""
>     print __func__.__doc__ # pseudo code
> 
> So basically, my question is: is there a way to access a function from
> within itself without using its name?


Well, I don't know if it's the best way to do it, but the 
following code I just threw together does the trick for me:

###########################################################
"A module docstring"
import inspect
def get_doc_string():
   frame = inspect.stack()[1]
   funcname = frame[3]
   try: # for straight functions
     return eval(funcname).__doc__
   except:
     locals = frame[0].f_locals
     try: # for object methods
       return getattr(locals["self"], funcname).__doc__
     except:
       try: # for class and module docstrings
         return locals["__doc__"]
       except:
         print "If you got here, there's something I missed"
         import pdb; pdb.set_trace()
         return funcname

if __name__ == "__main__":

   def outer_function():
     "A function docstring"
     s = get_doc_string()
     print s
     return s

   class Foo(object):
     "A class docstring"
     zip = get_doc_string()
     def bar(self):
       "A method's docstring"
       s = get_doc_string()
       print s
       return s

   def f1(func):
     "this is f1"
     s = func()
     print s
     return s

   test = outer_function()
   assert test == "A function docstring"
   foo = Foo()
   assert foo.bar() == "A method's docstring"
   print Foo.zip
   assert Foo.zip == "A class docstring"
   module_docstring = get_doc_string()
   print module_docstring
   assert module_docstring == "A module docstring"
   assert f1(get_doc_string) == "this is f1"

###########################################################

I couldn't find a handy way to get the actual 
function-object/class-object/module/method object for the given 
context without the convoluted try/except block.  Perhaps someone 
with more knowledge of the inspect module could reudce that do 
something far more simple.  There may also be problems if this is 
imported across modules.  But this might help point you in the 
right direction.

-tkc







More information about the Python-list mailing list