Skip to content

Instantly share code, notes, and snippets.

@perrygeo
Last active January 9, 2018 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save perrygeo/05ea61c699f8d02af49f04e193ab2655 to your computer and use it in GitHub Desktop.
Save perrygeo/05ea61c699f8d02af49f04e193ab2655 to your computer and use it in GitHub Desktop.
Decorator for aliasing kwargs in Python functions
#!/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)
@perrygeo
Copy link
Author

perrygeo commented Jan 8, 2018

⭆ python deprecated_kwargs.py
/tmp/try.py:15: DeprecationWarning: kwarg 'one' will be removed in version 1.0.0, switch to 'first' instead.
  category=DeprecationWarning)
/tmp/try.py:15: DeprecationWarning: kwarg 'two' will be removed in version 1.0.0, switch to 'second' instead.
  category=DeprecationWarning)
/tmp/try.py:15: DeprecationWarning: kwarg 'one' will be removed in version 1.0.0, switch to 'first' instead.
  category=DeprecationWarning)
/tmp/try.py:22: DeprecationWarning: Deprecated kwarg 'one' ignored, using 'first'
  category=DeprecationWarning)
/tmp/try.py:15: DeprecationWarning: kwarg 'two' will be removed in version 1.0.0, switch to 'second' instead.
  category=DeprecationWarning)
/tmp/try.py:22: DeprecationWarning: Deprecated kwarg 'two' ignored, using 'second'
  category=DeprecationWarning)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment