Search code examples
pythondecoratordocstringpython-decorators

How to print docstring outside a function using wrappers?


Quite related to about python __doc__ docstring. In case I don't use functools and use the wrapper as mentioned in How to print Docstring of python function from inside the function itself?, is there a way to get the docstring printed.

def passmein(func):
    def wrapper(*args, **kwargs):
        return func(func, *args, **kwargs)
    return wrapper

@passmein
def testfunc(me):
    """This is a test function"""
    #print me.__doc__

if __name__ == '__main__':
    print testfunc.__doc__

This returns none.


Solution

  • I'm not sure why you would not want to use functools.wraps, but you could add the doc string to wrapper yourself:

    def passmein(func):
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)
        wrapper.__doc__ = func.__doc__
        return wrapper
    
    @passmein
    def testfunc(me):
        """This is a test function"""
    
    if __name__ == '__main__':
        print testfunc.__doc__