Why does dynamic doc string do not work?

MRAB python at mrabarnett.plus.com
Tue Aug 21 13:16:45 EDT 2012


On 21/08/2012 17:44, Miki Tebeka wrote:
> Greetings,
>
>>>> class A:
> ...     '''a doc string'''
> ...
>>>> A.__doc__
> 'a doc string'
>>>> class B:
> ...     '''a {} string'''.format('doc')
> ...
>>>> B.__doc__
>>>>
>
> Is there's a reason for this?
>
> I know I can do:
>>>> class B:
> ...    __doc__ = '''a {} string'''.format('doc')
>
> And it'll work, but I wonder why the first B docstring is empty.
>
I think what's happening is that it's being parsed and then checked to
see whether it's a string literal.

This:

     "doc string"

is OK, as is this:

     "doc" "string"

(implied concatenation) and this:

    ("doc string")

but this isn't:

     "doc" + " string"

because its syntax is:

     ADD(STRING_LITERAL, STRING_LITERAL)

In other words, it's looking at the syntax, not the resulting value.



More information about the Python-list mailing list