Setting docstring to expression inside def

I would like to set func_doc(as an expression) inside 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 it possible?

(two reasons I can do this: import a function from a module (and you also want to import a docstring) and use lexer .)

+3
source share
4 answers

You cannot do this, since only a string literal is recognized as a docstring. But you can use the decorator to set or change the docstring function. (You can also explicitly change __doc__the executable code, but the decorator is much cleaner because it is logically part of the declaration).

, , , , () docstring. , ( ) docstring.

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

:

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

, (, ):

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

. : A , docstring. , , , .

docstring , . , . :

+1

, docstring , ( ).

python, docstring ( def), , docstring. Python function(), docstring ( ).

, , "" ; python , . , " " docstring .

docstring - __doc__ func_doc ( ). , , , docstring , .

, docstring:

>>> import itertools
>>> print itertools.groupby.__doc__
groupby(iterable[, keyfunc]) -> create an iterator which returns
(key, sub-iterator) grouped by each value of key(value).

docstring .

+1

__doc__ :

>>> def what():
...    """docstring"""
...    what.__doc__ += " x"
...    print what.__doc__
... 
>>> what()
docstring x
>>> what()
docstring x x
>>> what()
docstring x x x
>>> what()
docstring x x x x
0

Source: https://habr.com/ru/post/1660314/


All Articles