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

> 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.

I'm probably not understanding what you're asking, then. If you get the
docstring of the code object, that seems to be what you asked for, no?

The docstring “of the script” might be the docstring of the module. If
that's what you want, you can get the module, then access that module's
'__doc__' attribute.

If you don't know how to get the module, then it seems you have a new
question to ask: how to get from (whatever it is you currently have) to
the module. But, not really knowing what it is you're starting with, I
can't say better than that.

--
\ “I took it easy today. I just pretty much layed around in my |
`\ underwear all day. … Got kicked out of quite a few places, |
_o__) though.” —Bug-Eyed Earl, _Red Meat_ |
Ben Finney
From: Steven D'Aprano on
On Thu, 01 Jul 2010 11:55:05 +0200, Thomas Jollans wrote:

> 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:


Nope, you're misinterpreting what you're seeing. Here's a counter-example
from Python 3.1:

>>> def f():
.... 999
.... return 42
....
>>> f.__code__.co_consts
(None, 42)


The docstring is None, unless the function definition is immediately
followed by a string literal, in which case the string literal is taken
as the docstring. Any other object is removed by the keyhole optimizer:

>>> import dis
>>> dis.dis(f)
3 0 LOAD_CONST 1 (42)
3 RETURN_VALUE

In older versions of Python, the keyhole optimizer was less clever.
Here's an example from 2.4:

>>> def f():
.... 999
.... return 42
....
>>> f.func_code.co_consts
(None, 999, 42)
>>> import dis
>>> dis.dis(f)
2 0 LOAD_CONST 1 (999)
3 POP_TOP

3 4 LOAD_CONST 2 (42)
7 RETURN_VALUE


Aside: Python's keyhole optimizer has removed unreachable string
constants (other than doc strings) at least since Python 1.5. But doing
the same to other object types had to wait until Python 2.5.



--
Steven
From: moerchendiser2k3 on
Great! Thanks a lot!

This is what I was looking for. :)

Bye, moerchendiser2k3