1

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.

VPfB
  • 14,927
  • 6
  • 41
  • 75
  • 1
    Maybe something like this? http://stackoverflow.com/questions/2693883/dynamic-function-docstring – idjaw Feb 27 '16 at 20:51
  • Question: why do you need the dictionary? If you know the function, why can't you just use the `__doc__` attribute? – cdarke Feb 27 '16 at 21:07
  • @cdarke All registered functions form an API. There is an associated help function, e.g. `get_help(function_name)` that needs such dict. – VPfB Feb 27 '16 at 21:15
  • Is `function_name` a text string or the function name? I still don't see why you need the dict. – cdarke Feb 27 '16 at 22:52
  • @cdarke function_name is a string in the real application. The functions are defined in several modules. A dict or other storage is needed to aggregate them into a single API. – VPfB Feb 27 '16 at 23:06
  • You can still get the function object from a string by inspecting the caller's namespace. – cdarke Feb 27 '16 at 23:15
  • @cdarke 1. Only selected functions are part of the API. 2. There is more information to store and that information cannot be obtained by inspection – VPfB Feb 28 '16 at 06:48

0 Answers0