Last active
February 6, 2019 02:33
-
-
Save charlesreid1/03d01a06036b86ee427f1becdcea7786 to your computer and use it in GitHub Desktop.
Using functools @wraps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from functools import wraps | |
''' | |
This is a brief demo of how and why | |
functools @wraps is useful. | |
Basically, the decorator invisibly | |
swaps out one function with another | |
wrapper function. Unfortunately it | |
also invisibly swaps out the __name__ | |
and __doc__ attributes, too. | |
@wraps preserves the original __name__ | |
and __doc__ attributes. | |
if you remove the @wraps(f) below, | |
the complain decorator still works, | |
but the name and docstring of the | |
wrapper function will be used | |
("g" in the code below), which is | |
probably not what you want. | |
If you add the @wraps(f), then the | |
name and docstring of the original | |
function will be used. | |
''' | |
def complain_first(f): | |
@wraps(f) | |
def g(*args,**kwargs): | |
"""A wrapper that just complains""" | |
print("Whine whine whine, so much work") | |
return f(*args,**kwargs) | |
return g | |
@complain_first | |
def example(): | |
"""This is an example function""" | |
print("Called example function") | |
example() | |
print("Name string: ",example.__name__) | |
print("Doc string: ",example.__doc__) | |
''' | |
Output: | |
$ python wrap.py | |
Whine whine whine, so much work | |
Called example function | |
Name string: example | |
Doc string: This is an example function | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment