1
# Copyright (C) 2006-2010 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
The methods here allow for api symbol versioning.
22
from __future__ import absolute_import
24
__all__ = ['deprecated_function',
28
'DEPRECATED_PARAMETER',
36
# Import the 'warn' symbol so breezy can call it even if we redefine it
37
from warnings import warn
42
DEPRECATED_PARAMETER = "A deprecated parameter marker."
45
def deprecated_in(version_tuple):
46
"""Generate a message that something was deprecated in a release.
48
>>> deprecated_in((1, 4, 0))
49
'%s was deprecated in version 1.4.0.'
51
return ("%%s was deprecated in version %s."
52
% breezy._format_version_tuple(version_tuple))
55
def set_warning_method(method):
56
"""Set the warning method to be used by this module.
58
It should take a message and a warning category as warnings.warn does.
64
# TODO - maybe this would be easier to use as one 'smart' method that
65
# guess if it is a method or a class or an attribute ? If so, we can
66
# add that on top of the primitives, once we have all three written
70
def deprecation_string(a_callable, deprecation_version):
71
"""Generate an automatic deprecation string for a_callable.
73
:param a_callable: The callable to substitute into deprecation_version.
74
:param deprecation_version: A deprecation format warning string. This
75
should have a single %s operator in it. a_callable will be turned into
76
a nice python symbol and then substituted into deprecation_version.
78
if getattr(a_callable, '__self__', None) is not None:
79
symbol = "%s.%s.%s" % (a_callable.__self__.__class__.__module__,
80
a_callable.__self__.__class__.__name__,
82
elif getattr(a_callable, '__qualname__', None) is not None and '<' not in a_callable.__qualname__:
83
symbol = "%s.%s" % (a_callable.__module__,
84
a_callable.__qualname__)
86
symbol = "%s.%s" % (a_callable.__module__,
88
return deprecation_version % symbol
91
def deprecated_function(deprecation_version):
92
"""Decorate a function so that use of it will trigger a warning."""
94
def function_decorator(callable):
95
"""This is the function python calls to perform the decoration."""
97
def decorated_function(*args, **kwargs):
98
"""This is the decorated function."""
100
trace.mutter_callsite(4, "Deprecated function called")
101
warn(deprecation_string(callable, deprecation_version),
102
DeprecationWarning, stacklevel=2)
103
return callable(*args, **kwargs)
104
_populate_decorated(callable, deprecation_version, "function",
106
return decorated_function
107
return function_decorator
110
def deprecated_method(deprecation_version):
111
"""Decorate a method so that use of it will trigger a warning.
113
To deprecate a static or class method, use
119
To deprecate an entire class, decorate __init__.
122
def method_decorator(callable):
123
"""This is the function python calls to perform the decoration."""
125
def decorated_method(self, *args, **kwargs):
126
"""This is the decorated method."""
128
if callable.__name__ == '__init__':
129
symbol = "%s.%s" % (self.__class__.__module__,
130
self.__class__.__name__,
133
symbol = "%s.%s.%s" % (self.__class__.__module__,
134
self.__class__.__name__,
137
trace.mutter_callsite(4, "Deprecated method called")
138
warn(deprecation_version %
139
symbol, DeprecationWarning, stacklevel=2)
140
return callable(self, *args, **kwargs)
141
_populate_decorated(callable, deprecation_version, "method",
143
return decorated_method
144
return method_decorator
147
def deprecated_passed(parameter_value):
148
"""Return True if parameter_value was used."""
149
# FIXME: it might be nice to have a parameter deprecation decorator.
150
# it would need to handle positional and *args and **kwargs parameters,
151
# which means some mechanism to describe how the parameter was being
152
# passed before deprecation, and some way to deprecate parameters that
153
# were not at the end of the arg list. Thats needed for __init__ where
154
# we cannot just forward to a new method name.I.e. in the following
155
# examples we would want to have callers that pass any value to 'bad' be
156
# given a warning - because we have applied:
157
# @deprecated_parameter('bad', deprecated_in((1, 5, 0))
159
# def __init__(self, bad=None)
160
# def __init__(self, bad, other)
161
# def __init__(self, **kwargs)
163
return parameter_value is not DEPRECATED_PARAMETER
166
def _decorate_docstring(callable, deprecation_version, label,
169
docstring_lines = callable.__doc__.split('\n')
172
if len(docstring_lines) == 0:
173
decorated_callable.__doc__ = deprecation_version % ("This " + label)
174
elif len(docstring_lines) == 1:
175
decorated_callable.__doc__ = (
176
callable.__doc__ + "\n" + "\n" +
177
deprecation_version % ("This " + label) + "\n")
179
spaces = len(docstring_lines[-1])
180
new_doc = callable.__doc__
181
new_doc += "\n" + " " * spaces
182
new_doc += deprecation_version % ("This " + label)
183
new_doc += "\n" + " " * spaces
184
decorated_callable.__doc__ = new_doc
187
def _populate_decorated(callable, deprecation_version, label,
189
"""Populate attributes like __name__ and __doc__ on the decorated callable.
191
_decorate_docstring(callable, deprecation_version, label,
193
decorated_callable.__module__ = callable.__module__
194
decorated_callable.__name__ = callable.__name__
195
decorated_callable.is_deprecated = True
198
def _dict_deprecation_wrapper(wrapped_method):
199
"""Returns a closure that emits a warning and calls the superclass"""
200
def cb(dep_dict, *args, **kwargs):
201
msg = 'access to %s' % (dep_dict._variable_name, )
202
msg = dep_dict._deprecation_version % (msg,)
204
msg += ' ' + dep_dict._advice
205
warn(msg, DeprecationWarning, stacklevel=2)
206
return wrapped_method(dep_dict, *args, **kwargs)
210
class DeprecatedDict(dict):
211
"""A dictionary that complains when read or written."""
221
"""Create a dict that warns when read or modified.
223
:param deprecation_version: string for the warning format to raise,
224
typically from deprecated_in()
225
:param initial_value: The contents of the dict
226
:param variable_name: This allows better warnings to be printed
227
:param advice: String of advice on what callers should do instead
228
of using this variable.
230
self._deprecation_version = deprecation_version
231
self._variable_name = variable_name
232
self._advice = advice
233
dict.__init__(self, initial_value)
235
# This isn't every possible method but it should trap anyone using the
236
# dict -- add more if desired
237
__len__ = _dict_deprecation_wrapper(dict.__len__)
238
__getitem__ = _dict_deprecation_wrapper(dict.__getitem__)
239
__setitem__ = _dict_deprecation_wrapper(dict.__setitem__)
240
__delitem__ = _dict_deprecation_wrapper(dict.__delitem__)
241
keys = _dict_deprecation_wrapper(dict.keys)
242
__contains__ = _dict_deprecation_wrapper(dict.__contains__)
245
def deprecated_list(deprecation_version, variable_name,
246
initial_value, extra=None):
247
"""Create a list that warns when modified
249
:param deprecation_version: string for the warning format to raise,
250
typically from deprecated_in()
251
:param initial_value: The contents of the list
252
:param variable_name: This allows better warnings to be printed
253
:param extra: Extra info to print when printing a warning
256
subst_text = 'Modifying %s' % (variable_name,)
257
msg = deprecation_version % (subst_text,)
261
class _DeprecatedList(list):
262
__doc__ = list.__doc__ + msg
266
def _warn_deprecated(self, func, *args, **kwargs):
267
warn(msg, DeprecationWarning, stacklevel=3)
268
return func(self, *args, **kwargs)
270
def append(self, obj):
271
"""appending to %s is deprecated""" % (variable_name,)
272
return self._warn_deprecated(list.append, obj)
274
def insert(self, index, obj):
275
"""inserting to %s is deprecated""" % (variable_name,)
276
return self._warn_deprecated(list.insert, index, obj)
278
def extend(self, iterable):
279
"""extending %s is deprecated""" % (variable_name,)
280
return self._warn_deprecated(list.extend, iterable)
282
def remove(self, value):
283
"""removing from %s is deprecated""" % (variable_name,)
284
return self._warn_deprecated(list.remove, value)
286
def pop(self, index=None):
287
"""pop'ing from %s is deprecated""" % (variable_name,)
289
return self._warn_deprecated(list.pop, index)
292
return self._warn_deprecated(list.pop)
294
return _DeprecatedList(initial_value)
297
def _check_for_filter(error_only):
298
"""Check if there is already a filter for deprecation warnings.
300
:param error_only: Only match an 'error' filter
301
:return: True if a filter is found, False otherwise
303
for filter in warnings.filters:
304
if issubclass(DeprecationWarning, filter[2]):
305
# This filter will effect DeprecationWarning
306
if not error_only or filter[0] == 'error':
311
def _remove_filter_callable(filter):
312
"""Build and returns a callable removing filter from the warnings.
314
:param filter: The filter to remove (can be None).
316
:return: A callable that will remove filter from warnings.filters.
321
warnings.filters.remove(filter)
322
except (ValueError, IndexError):
327
def suppress_deprecation_warnings(override=True):
328
"""Call this function to suppress all deprecation warnings.
330
When this is a final release version, we don't want to annoy users with
331
lots of deprecation warnings. We only want the deprecation warnings when
332
running a dev or release candidate.
334
:param override: If True, always set the ignore, if False, only set the
335
ignore if there isn't already a filter.
337
:return: A callable to remove the new warnings this added.
339
if not override and _check_for_filter(error_only=False):
340
# If there is already a filter effecting suppress_deprecation_warnings,
344
warnings.filterwarnings('ignore', category=DeprecationWarning)
345
filter = warnings.filters[0]
346
return _remove_filter_callable(filter)
349
def activate_deprecation_warnings(override=True):
350
"""Call this function to activate deprecation warnings.
352
When running in a 'final' release we suppress deprecation warnings.
353
However, the test suite wants to see them. So when running selftest, we
354
re-enable the deprecation warnings.
356
Note: warnings that have already been issued under 'ignore' will not be
357
reported after this point. The 'warnings' module has already marked them as
358
handled, so they don't get issued again.
360
:param override: If False, only add a filter if there isn't an error filter
361
already. (This slightly differs from suppress_deprecation_warnings, in
362
because it always overrides everything but -Werror).
364
:return: A callable to remove the new warnings this added.
366
if not override and _check_for_filter(error_only=True):
367
# DeprecationWarnings are already turned into errors, don't downgrade
371
warnings.filterwarnings('default', category=DeprecationWarning)
372
filter = warnings.filters[0]
373
return _remove_filter_callable(filter)