There is a small problem with the following code:
docs = {}
def register(func):
docs[func] = func.__doc__
return func
@register
def blue():
"""Color function."""
pass
@register
def red():
pass
red.__doc__ = blue.__doc__
print("docstring real:", red.__doc__)
print("docstring registered:", docs[red]) # None!
The red
function gets its docstring from the blue
function. But this happens after the decorator registers it.
I could add an optional argument to the register
decorator, but this case is not special enough. It looks like I have to copy and paste the string. No problem with that ... except that I'm still wondering if there is an trivial fix that I have overlooked.
UPDATE: After realizing that @decorator
is just a syntactic sugar I've found a workaround:
# @register
def red():
pass
red.__doc__ = blue.__doc__
red = register(red)
This solves my problem.
The docstring is still created after the function definition. For an answer to the original question see the comment added by idjaw.