__doc__ of current function?

Sean Ross seandavidross at hotmail.com
Thu Sep 2 13:51:58 CEST 2004


"Peter Otten" <__peter__ at web.de> wrote in message
news:ch6uj8$t68$00$1 at news.t-online.com...
> 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
>


Hi.
Yes, it fails for methods:

>>> import sys
>>> def caller():
...  f = sys._getframe(1)
...  return f.f_globals[f.f_code.co_name]
...
>>> class C:
...  def m(self):
...   "mmmmmmmmmm"
...   print caller().__doc__
...
>>> c = C()
>>> c.m()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "<interactive input>", line 4, in m
  File "<interactive input>", line 3, in caller
KeyError: 'm'
>>>





More information about the Python-list mailing list