• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Licensed under the Apache License, Version 2.0 (the "License");
2# you may not use this file except in compliance with the License.
3# You may obtain a copy of the License at
4#
5#      http://www.apache.org/licenses/LICENSE-2.0
6#
7# Unless required by applicable law or agreed to in writing, software
8# distributed under the License is distributed on an "AS IS" BASIS,
9# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10# See the License for the specific language governing permissions and
11# limitations under the License.
12"""Utilities for handling deprecated functions."""
13
14import functools
15import warnings
16
17
18class Deprecator(object):
19    """Decorator class for adding deprecated functions.
20
21    Warnings are switched on by default.
22    To disable deprecation warnings, use:
23
24    >>> from pyfakefs.deprecator import Deprecator
25    >>>
26    >>> Deprecator.show_warnings = False
27    """
28
29    show_warnings = True
30
31    def __init__(self, use_instead=None, func_name=None):
32        self.use_instead = use_instead
33        self.func_name = func_name
34
35    def __call__(self, func):
36        """Decorator to mark functions as deprecated. Emit warning
37        when the function is used."""
38
39        @functools.wraps(func)
40        def _new_func(*args, **kwargs):
41            if self.show_warnings:
42                warnings.simplefilter('always', DeprecationWarning)
43                message = ''
44                if self.use_instead is not None:
45                    message = 'Use {} instead.'.format(self.use_instead)
46                warnings.warn('Call to deprecated function {}. {}'.format(
47                    self.func_name or func.__name__, message),
48                              category=DeprecationWarning, stacklevel=2)
49                warnings.simplefilter('default', DeprecationWarning)
50            return func(*args, **kwargs)
51
52        return _new_func
53
54    @staticmethod
55    def add(clss, func, deprecated_name):
56        """Add the deprecated version of a member function to the given class.
57        Gives a deprecation warning on usage.
58
59        Args:
60            clss: the class where the deprecated function is to be added
61            func: the actual function that is called by the deprecated version
62            deprecated_name: the deprecated name of the function
63        """
64
65        @Deprecator(func.__name__, deprecated_name)
66        def _old_function(*args, **kwargs):
67            return func(*args, **kwargs)
68
69        setattr(clss, deprecated_name, _old_function)
70