From: moerchendiser2k3 on
Hi all,

when I have a PyCodeObject, is there any way to extract a doc string
from the code?
For instance the following script

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

I would like to get "Hello World!". Any chance? Thanks in advance!!

Bye, moerchendiser2k3
From: Ben Finney on
moerchendiser2k3 <googler.1.webmaster(a)spamgourmet.com> writes:

> when I have a PyCodeObject, is there any way to extract a doc string
> from the code?

I'm not very familiar with using the C interface for Python, but does it
help to know that a docstring for an object is available at that
object's '__doc__' attribute?

--
\ “Time is the great legalizer, even in the field of morals.” |
`\ —Henry L. Mencken |
_o__) |
Ben Finney
From: moerchendiser2k3 on
Hi ben,

thanks for your answer. Sure, __doc__ is the access point to the
docstring, but in this case, I just get the docstring of the code
object. So an explanation what a code object, but I need the docstring
of real docstring of the script.

bye, moerchendiser
From: Jean-Michel Pichavant on
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
>
> <---script---->
> """
> Hello World!
> """
> def main():
> pass
> main()
> </---script--->
>
> I would like to get "Hello World!". Any chance? Thanks in advance!!
>
> Bye, moerchendiser2k3
>
Hello,


"""Hello world!!"""

import sys
def main():
print sys.modules[__name__].__doc__

main()



JM
From: Thomas Jollans on
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.