Jack Z Jack Z - 9 months ago 50
Python Question

How to put a variable into Python docstring

So I'm trying to create a "dynamic" docstring which is something like this:

ANIMAL_TYPES = ["mammals", "reptiles", "other"]

def func(animalType):
""" This is a sample function.

@param animalType: "It takes one of these animal types %s" % ANIMAL_TYPES

to basically let the docstring for
@param animalType
show whatever
has; so that when this variable is updated, the docstring will be updated automatically.

Unfortunately, however, it doesn't seem working... Does anyone know if there is a way of achieving this?


So taking the advice of Chris and Ashwini, I went with something like this:

Class MyClass:
MY_CONST = ['A', 'B']

def func(self, choice):
""" some text`
:param choice: can be one of %s
func.__doc__ %= MY_CONST

Answer Source

Triple-quoted strings are one big string. Nothing is evaluated inside them. The % part is all part of the string. You'd need to have it operating on the actual string.

def func(animalType):
    This is a sample function.

    @param animalType: "It takes one of these animal types %(ANIMAL_TYPES)s"

I'm not certain this will work properly, though; docstrings are a bit magic. This will not work; the docstring is evaluated at compile time (as the first statement in the function, given it is a string literal—once it's got the % in it it's not just a string literal), string formatting takes place at runtime, so __doc__ will be empty:

>>> def a(): 'docstring works'
>>> a.__doc__
'docstring works'
>>> def b(): "formatted docstring doesn't work %s" % ':-('
>>> b.__doc__

If you wanted to work this way, you'd need to do func.__doc__ %= {'ANIMAL_TYPES': ANIMAL_TYPES} after the function is defined. Be aware that this would then break on python -OO if you didn't check that __doc__ was defined, as -OO strips docstrings.

>>> def c(): "formatted docstring works %s"
>>> c.__doc__
"formatted docstring works %s"
>>> c.__doc__ %= 'after'
>>> c.__doc__
"formatted docstring works after"

This is not the standard technique anyway; the standard technique is to reference the appropriate constant: "Takes one of the animal types in ANIMAL_TYPES", or similar.