Last active
January 9, 2018 00:31
-
-
Save perrygeo/05ea61c699f8d02af49f04e193ab2655 to your computer and use it in GitHub Desktop.
Decorator for aliasing kwargs in Python functions
This file contains 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
#!/usr/bin/env python | |
import warnings | |
from functools import wraps | |
def deprecated_kwarg(old, new, version): | |
def decorator(func): | |
@wraps(func) | |
def func_wrapper(*args, **kwargs): | |
new_kwargs = kwargs.copy() | |
if old in kwargs: | |
warnings.warn( | |
"kwarg '{}' will be removed in version {}" | |
", switch to '{}' instead.".format(old, version, new), | |
category=DeprecationWarning) | |
del new_kwargs[old] | |
if new in kwargs: | |
warnings.warn( | |
"Deprecated kwarg '{}' ignored, using '{}'".format(old, new), | |
category=DeprecationWarning) | |
else: | |
new_kwargs[new] = kwargs[old] | |
return func(*args, **new_kwargs) | |
return func_wrapper | |
return decorator | |
# Tests | |
if __name__ == "__main__": | |
def add(one, two): | |
return one + two | |
@deprecated_kwarg(old='one', new='first', version='1.0.0') | |
@deprecated_kwarg(old='two', new='second', version='1.0.0') | |
def add2(first, second): | |
return first + second | |
warnings.simplefilter('always', DeprecationWarning) | |
assert \ | |
add(1, 2) == \ | |
add2(1, 2) == \ | |
add(one=1, two=2) == \ | |
add2(first=1, second=2) == \ | |
add2(one=1, two=2) == \ | |
add2(one=1, first=1, two=2, second=2) | |
warnings.simplefilter('default', DeprecationWarning) |
Author
perrygeo
commented
Jan 8, 2018
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment