Python Decorators With @wraps

Using decorators can be very helpful and useful way to wrap functions in python but it can be very hard to debug the code with them.

Since decorator is simply a function that wraps original one so it will replace main function’s .name property to it’s own name and reset .doc that can cause some misunderstanding during debugging process. 

An easy way to deal with this problem is using python wraps decorator

from functools import wraps

 def simple_decorator(func):
    def __wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return __wrapper

def with_wraps(func):
    @wraps(func)
    def __wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return __wrapper


@simple_decorator
def simple():
    """Here is simple doc string text."""
    pass

@with_wraps
def wrapper():
    """Here is wrapper doc string text."""
    pass


# without using @wraps decorator
print simple.__doc__
#>>> None
print simple.__name__
#>>> __wrapper

# using @wraps decorator
print wrapper.__doc__
#>>> Here is wrapper doc string text.
print wrapper.__name__
#>>> wrapper
 
7
Kudos
 
7
Kudos