Created
November 11, 2019 14:35
-
-
Save kbob/022f5ee8ea11f07bf890acf388e5919e to your computer and use it in GitHub Desktop.
Python Decorator with Optional Keyword Arguments
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
""" | |
Function decorator with optional keyword arguments. | |
""" | |
from functools import wraps | |
def decorate(func=None, kind=''): | |
if func is None: | |
# was called pre-decoration. Return anonymous decorator. | |
return lambda f: decorate(f, kind) | |
# Normal case: decorate passed function. | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
return f'{kind}wrapped ' + func(*args, **kwargs) | |
return wrapper | |
# Decorate function with default options.. | |
@decorate | |
def foo(arg): | |
"""This is foo.""" | |
return f'foo(arg={arg})' | |
result = foo(3) | |
assert result == 'wrapped foo(arg=3)' | |
assert foo.__name__ == 'foo' | |
assert foo.__doc__ == 'This is foo.' | |
# Decorate function with changed option. | |
@decorate(kind='gift ') | |
def bar(arg): | |
"""This is bar.""" | |
return f'bar(arg={arg})' | |
result = bar(3) | |
assert result == 'gift wrapped bar(arg=3)' | |
assert bar.__name__ == 'bar' | |
assert bar.__doc__ == 'This is bar.' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment