Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ANIMAL_TYPES has; so that when this variable is updated, the docstring will be updated automatically.

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

like image 880
Jack Z Avatar asked Apr 25 '12 00:04

Jack Z


People also ask

Can docstrings be assigned to variables?

Yes, you can do that! You can actually 'document' lambdas and variables in a module by attaching docstrings to them.

How do you add a docstring in Python?

Declaring Docstrings: The docstrings are declared using ”'triple single quotes”' or “””triple double quotes””” just below the class, method or function declaration. All functions should have a docstring.

What do you put in a docstring?

Class method docstrings should contain the following: A brief description of what the method is and what it's used for. Any arguments (both required and optional) that are passed including keyword arguments. Label any arguments that are considered optional or have a default value.

How do you write a docstring for a function?

Docstrings must be defined with three double-quotes. No blank lines should be left before or after the docstring. The text starts in the next line after the opening quotes. The closing quotes have their own line (meaning that they are not at the end of the last sentence).


1 Answers

One way to do this would be to use a decorator. I'm not sure how I feel about this; I actually searched for commentary on this method and found this answer, which rightly notes that it could mask a design problem. But your use case seems sound to me at first glance.

In any case, here's a fairly elegant way to achieve the result you're looking for:

>>> def docstring_parameter(*sub): ...     def dec(obj): ...         obj.__doc__ = obj.__doc__.format(*sub) ...         return obj ...     return dec ...  >>> @docstring_parameter('Ocean') ... def foo(): ...     '''My Docstring Lies Over The {0}''' ...     pass ...  >>> @docstring_parameter('Sea') ... def bar(): ...     '''My Docstring Lies Over The {0}''' ...     pass ...  >>> @docstring_parameter('Docstring', 'Me') ... def baz(): ...     '''Oh Bring Back My {0} To {1}''' ...     pass ...  >>> foo.__doc__ 'My Docstring Lies Over The Ocean' >>> bar.__doc__ 'My Docstring Lies Over The Sea' >>> foo.__doc__ 'My Docstring Lies Over The Ocean' >>> baz.__doc__ 'Oh Bring Back My Docstring To Me' 
like image 188
senderle Avatar answered Sep 26 '22 01:09

senderle