Extract doc strings

Thomas Jollans thomas at jollans.com
Thu Jul 1 05:55:05 EDT 2010


On 07/01/2010 11:12 AM, moerchendiser2k3 wrote:
> Hi all,
> 
> when I have a PyCodeObject, is there any way to extract a doc string
> from the code?
> For instance the following script

Code objects don't have doc strings, as such. However, for functions at
least (this may or may not be true for code originating elsewhere), it
appears that the code's first constant is always the docstring, even if
it's None:


>>> def f(a=()):
...     """doc string"""
...     return 1,2,3,a
...
>>> def g(a=[], b=0):
...     return False
...
>>> f.__code__.co_consts
('doc string', 1, 2, 3)
>>> g.__code__.co_consts
(None, False)
>>>

Why else would g.__code__.co_consts[0] be None if that wasn't a
docstring-specific special place. I don't know how you're creating your
codeobject, and I don't know if this holds for your case.

-- Thomas

> 
> <---script---->
> """
> Hello World!
> """
> def main():
>     pass
> main()
> </---script--->

This looks like something that should usually be accessed as a module,
and in that case, it's trivial, as others have pointed out.



More information about the Python-list mailing list