__doc__ of current function?

Peter Otten __peter__ at web.de
Thu Sep 2 07:02:00 EDT 2004


Ksenia Marasanova wrote:

>>
>> ... can I write a general docOfCurrentFunction() function so that I
>> can rewrite it:
>>
>> def validatePassword(p):
>>    'do something'
>>    print docOfCurrentFunction()
>>
> 
> def docOfCurrentFunction():
>      import sys
>      func_name = sys._getframe(1).f_code.co_name
>      return eval(func_name + '.__doc__')
> 
> But I hope that a more intelligent way exists than using 'eval' :)

Maybe

>>> import sys
>>> def caller():
...     f = sys._getframe(1)
...     return f.f_globals[f.f_code.co_name]
...
>>> def demo():
...     "Demo docstring"
...     print caller().__doc__
...
>>> demo()
Demo docstring
>>>

Or can that fail in some cases?

Peter




More information about the Python-list mailing list