Search code examples
pythondocstring

Setting the docstring to an expression inside def


I would like to set the func_doc (as an expression) within def.

def f():
    '''My function help''' #Set the docstring

def g():
    "My function " + "help" # An expression, so not read as a docstring
    # can I put something here to set the docstring as an expression?
g.func_doc # is None
g.func_doc = "My function " + "help" # This works

Is this possible?

(two reasons I can think for doing this: importing a function from a module (and you want to import the docstring too) and using a lexer.)


Solution

  • You can't do that, since only a string literal is recognized as a docstring. But you can use a decorator to set or modify a function's docstring. (You can also modify __doc__ explicitly in executable code, but a decorator is much cleaner since it is logically part of the declaration).

    This can be useful, for example, if you have several functions that should contain the same text as (part of) their docstring. Here's a little decorator that appends its argument (literal or a variable) to a function's declared docstring.

    def docstring(docstr, sep="\n"):
        """
        Decorator: Append to a function's docstring.
        """
        def _decorator(func):
            if func.__doc__ is None:
                func.__doc__ = docstr
            else:
                func.__doc__ = sep.join([func.__doc__, docstr])
            return func
        return _decorator
    

    It can be used like this:

    @docstring("copyright by nobody")
    def testme():
        "This function does nothing"
        pass
    

    Or you can execute it directly, to modify an existing function (perhaps imported from another module):

    from re import sub
    docstring("Copyright unknown")(sub)