aboutsummaryrefslogtreecommitdiff
path: root/pyfakefs/deprecator.py
blob: 99d0ae619043edc29447057979281bc584864e82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utilities for handling deprecated functions."""

import functools
import warnings


class Deprecator(object):
    """Decorator class for adding deprecated functions.

    Warnings are switched on by default.
    To disable deprecation warnings, use:

    >>> from pyfakefs.deprecator import Deprecator
    >>>
    >>> Deprecator.show_warnings = False
    """

    show_warnings = True

    def __init__(self, use_instead=None, func_name=None):
        self.use_instead = use_instead
        self.func_name = func_name

    def __call__(self, func):
        """Decorator to mark functions as deprecated. Emit warning
        when the function is used."""

        @functools.wraps(func)
        def _new_func(*args, **kwargs):
            if self.show_warnings:
                with warnings.catch_warnings():
                    warnings.simplefilter('always', DeprecationWarning)
                    message = ''
                    if self.use_instead is not None:
                        message = 'Use {} instead.'.format(self.use_instead)
                    warnings.warn('Call to deprecated function {}. {}'.format(
                        self.func_name or func.__name__, message),
                                  category=DeprecationWarning, stacklevel=2)
            return func(*args, **kwargs)

        return _new_func

    @staticmethod
    def add(clss, func, deprecated_name):
        """Add the deprecated version of a member function to the given class.
        Gives a deprecation warning on usage.

        Args:
            clss: the class where the deprecated function is to be added
            func: the actual function that is called by the deprecated version
            deprecated_name: the deprecated name of the function
        """

        @Deprecator(func.__name__, deprecated_name)
        def _old_function(*args, **kwargs):
            return func(*args, **kwargs)

        setattr(clss, deprecated_name, _old_function)