Add a 'removed_kwarg' function/method decorator

It is quite often useful to deprecate a keyword argument
so that it can be either removed or replaced in the near
future; so a decorator that aids in this pattern can be
quite useful for others.

Change-Id: Ic57f93722b113c2aa900b2b92aa90174aadc7904
This commit is contained in:
Joshua Harlow 2015-02-12 14:20:34 -08:00
parent 538299d29f
commit 3d9e38f750
2 changed files with 41 additions and 0 deletions

View File

@ -16,6 +16,7 @@ import functools
import inspect
from oslo_utils import reflection
import six
import wrapt
from debtcollector import _utils
@ -92,3 +93,25 @@ def remove(f=None, message=None, version=None, removal_version=None,
_utils.deprecation(out_message, stacklevel)
return f(*args, **kwargs)
return wrapper(f)
def removed_kwarg(old_name, message=None,
version=None, removal_version=None, stacklevel=3):
"""Decorates a kwarg accepting function to deprecate a removed kwarg."""
prefix = "Using the '%s' argument is deprecated" % old_name
out_message = _utils.generate_message(
prefix, postfix=None, message=message, version=version,
removal_version=removal_version)
def decorator(f):
@six.wraps(f)
def wrapper(*args, **kwargs):
if old_name in kwargs:
_utils.deprecation(out_message, stacklevel=stacklevel)
return f(*args, **kwargs)
return wrapper
return decorator

View File

@ -188,6 +188,24 @@ class RemovalTests(test_base.TestCase):
def test_function_noargs(self):
self.assertTrue(red_comet())
def test_deprecated_kwarg(self):
@removals.removed_kwarg('b')
def f(b=2):
return b
with warnings.catch_warnings(record=True) as capture:
warnings.simplefilter("always")
self.assertEqual(3, f(b=3))
self.assertEqual(1, len(capture))
w = capture[0]
self.assertEqual(DeprecationWarning, w.category)
with warnings.catch_warnings(record=True) as capture:
warnings.simplefilter("always")
self.assertEqual(2, f())
self.assertEqual(0, len(capture))
def test_warnings_emitted_function_args(self):
with warnings.catch_warnings(record=True) as capture:
warnings.simplefilter("always")