__doc__ in compiled script

Peter Otten __peter__ at web.de
Thu Nov 2 15:54:11 EST 2006


Gabriel Genellina wrote:

> Hello
> 
> I have a script starting with a docstring. After compiling it with
> compile(), is there any way I could get the docstring? __doc__ on the
> code object doesn't work.
> I can't use __import__ because the script has top-level statements
> that have to be executed only once (it's not supposed to be used as a
> module).
> 
> --- begin test.py ---
> body = """
> "This is a docstring"
> 
> x=0
> some(code).toBeExecuted("later")
> """
> 
> co = compile(body,'<string>','exec')
> print co.__doc__
> 
> # what can I use for "something" below: ?
> assert something(co)=="This is a docstring"
> --- end test.py ---

>>> co.co_consts[list(co.co_names).index("__doc__")]
'This is a docstring'

or probably just

>>> co.co_consts[0]
'This is a docstring'

as I cannot imaginge the docstring to have a non-zero index.

Peter




More information about the Python-list mailing list