summaryrefslogtreecommitdiff
path: root/logilab/common/deprecation.py
blob: cdf538c12a9d7920d312ae949f883bb0f53e5578 (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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# copyright 2003-2012 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of logilab-common.
#
# logilab-common is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 2.1 of the License, or (at your option) any
# later version.
#
# logilab-common is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with logilab-common.  If not, see <http://www.gnu.org/licenses/>.
"""Deprecation utilities."""

__docformat__ = "restructuredtext en"

import os
import sys
from warnings import warn
from functools import wraps

from logilab.common.changelog import Version


class DeprecationWrapper(object):
    """proxy to print a warning on access to any attribute of the wrapped object
    """
    def __init__(self, proxied, msg=None):
        self._proxied = proxied
        self._msg = msg

    def __getattr__(self, attr):
        warn(self._msg, DeprecationWarning, stacklevel=2)
        return getattr(self._proxied, attr)

    def __setattr__(self, attr, value):
        if attr in ('_proxied', '_msg'):
            self.__dict__[attr] = value
        else:
            warn(self._msg, DeprecationWarning, stacklevel=2)
            setattr(self._proxied, attr, value)


class DeprecationManager(object):
    """Manage the deprecation message handling. Messages are dropped for
    versions more recent than the 'compatible' version. Example::

        deprecator = deprecation.DeprecationManager("module_name")
        deprecator.compatibility('1.3')

        deprecator.warn('1.2', "message.")

        @deprecator.deprecated('1.2', 'Message')
        def any_func():
            pass

        class AnyClass(object):
            __metaclass__ = deprecator.class_deprecated('1.2')
    """
    def __init__(self, module_name=None):
        """
        """
        self.module_name = module_name
        self.compatible_version = None

    def compatibility(self, compatible_version):
        """Set the compatible version.
        """
        self.compatible_version = Version(compatible_version)

    def deprecated(self, version=None, reason=None, stacklevel=2, name=None, doc=None):
        """Display a deprecation message only if the version is older than the
        compatible version.
        """
        def decorator(func):
            message = reason or 'The function "%s" is deprecated'
            if '%s' in message:
                message %= func.__name__

            @wraps(func)
            def wrapped(*args, **kwargs):
                self.warn(version, message, stacklevel+1)
                return func(*args, **kwargs)
            return wrapped
        return decorator

    def class_deprecated(self, version=None):
        class metaclass(type):
            """metaclass to print a warning on instantiation of a deprecated class"""

            def __call__(cls, *args, **kwargs):
                msg = getattr(cls, "__deprecation_warning__",
                              "%(cls)s is deprecated") % {'cls': cls.__name__}
                self.warn(version, msg, stacklevel=3)
                return type.__call__(cls, *args, **kwargs)
        return metaclass

    def moved(self, version, modpath, objname):
        """use to tell that a callable has been moved to a new module.

        It returns a callable wrapper, so that when its called a warning is printed
        telling where the object can be found, import is done (and not before) and
        the actual object is called.

        NOTE: the usage is somewhat limited on classes since it will fail if the
        wrapper is use in a class ancestors list, use the `class_moved` function
        instead (which has no lazy import feature though).
        """
        def callnew(*args, **kwargs):
            from logilab.common.modutils import load_module_from_name
            message = "object %s has been moved to module %s" % (objname, modpath)
            self.warn(version, message)
            m = load_module_from_name(modpath)
            return getattr(m, objname)(*args, **kwargs)
        return callnew

    def renamed(self, old_name, new_function):
        """use to tell that a callable has been renamed.

        It returns a callable wrapper, so that when its called a warning is printed
        telling what is the object new name.
        """
        @wraps(new_function)
        def wrapped(*args, **kwargs):
            self.warn(None, (
                f"{old_name} has been renamed and is deprecated, uses {new_function.__name__} "
                f"instead"
            ), stacklevel=3)
            return new_function(*args, **kwargs)
        return wrapped

    def class_renamed(self, version, old_name, new_class, message=None):
        clsdict = {}
        if message is None:
            message = '%s is deprecated, use %s' % (old_name, new_class.__name__)
        clsdict['__deprecation_warning__'] = message
        try:
            # new-style class
            return self.class_deprecated(version)(old_name, (new_class,), clsdict)
        except (NameError, TypeError):
            # old-style class
            warn = self.warn
            class DeprecatedClass(new_class):
                """FIXME: There might be a better way to handle old/new-style class
                """
                def __init__(self, *args, **kwargs):
                    warn(version, message, stacklevel=3)
                    new_class.__init__(self, *args, **kwargs)
            return DeprecatedClass

    def class_moved(self, version, new_class, old_name=None, message=None):
        """nice wrapper around class_renamed when a class has been moved into
        another module
        """
        if old_name is None:
            old_name = new_class.__name__
        if message is None:
            message = 'class %s is now available as %s.%s' % (
                old_name, new_class.__module__, new_class.__name__)
        return self.class_renamed(version, old_name, new_class, message)

    def warn(self, version=None, reason="", stacklevel=2):
        """Display a deprecation message only if the version is older than the
        compatible version.
        """
        if (self.compatible_version is None
            or version is None
            or Version(version) < self.compatible_version):
            if self.module_name and version:
                reason = '[%s %s] %s' % (self.module_name, version, reason)
            elif self.module_name:
                reason = '[%s] %s' % (self.module_name, reason)
            elif version:
                reason = '[%s] %s' % (version, reason)
            warn(reason, DeprecationWarning, stacklevel=stacklevel)


_defaultdeprecator = DeprecationManager()


def _get_package_name(number=2):
    """
    automagically try to determine the package name from which the warning has
    been triggered by loop other calling frames.

    If it fails to do so, return an empty string.
    """

    frame = sys._getframe()

    for i in range(number):
        if frame.f_back is None:
            break

        frame = frame.f_back

    if frame.f_globals["__package__"] is not None:
        return frame.f_globals["__package__"]

    file_name = os.path.split(frame.f_globals["__file__"])[1]

    if file_name.endswith(".py"):
        file_name = file_name[:-len(".py")]

    return file_name


def send_warning(reason, version=None, stacklevel=2):
    """Display a deprecation message only if the version is older than the
    compatible version.
    """
    module_name = _get_package_name(stacklevel + 1)

    if module_name and version:
        reason = '[%s %s] %s' % (module_name, version, reason)
    elif module_name:
        reason = '[%s] %s' % (module_name, reason)
    elif version:
        reason = '[%s] %s' % (version, reason)

    warn(reason, DeprecationWarning, stacklevel=stacklevel)


def argument_removed(old_argument_name):
    """
    callable decorator to allow getting backward compatibility for renamed keyword arguments.

    >>> @argument_removed("old")
    ... def some_function(new):
    ...     return new
    >>> some_function(old=42)
    sample.py:15: DeprecationWarning: argument old of callable some_function has been renamed and is deprecated, use keyword argument new instead
      some_function(old=42)
    42
    """
    def _wrap(func):
        @wraps(func)
        def check_kwargs(*args, **kwargs):
            if old_argument_name in kwargs:
                warn(f"argument {old_argument_name} of callable {func.__name__} has been removed and is "
                     f"deprecated", stacklevel=2)
                del kwargs[old_argument_name]

            return func(*args, **kwargs)

        return check_kwargs

    return _wrap


@argument_removed("name")
@argument_removed("doc")
def deprecated(reason=None, version=None, stacklevel=2):
    """Display a deprecation message only if the version is older than the
    compatible version.
    """
    def decorator(func):
        message = reason or 'The function "%s" is deprecated'
        if '%s' in message:
            message %= func.__name__

        @wraps(func)
        def wrapped(*args, **kwargs):
            send_warning(message, version, stacklevel + 1)
            return func(*args, **kwargs)
        return wrapped

    return decorator


class class_deprecated(type):
    """metaclass to print a warning on instantiation of a deprecated class"""

    def __call__(cls, *args, **kwargs):
        msg = getattr(cls, "__deprecation_warning__",
                      "%(cls)s is deprecated") % {'cls': cls.__name__}
        send_warning(msg, stacklevel=4)
        return type.__call__(cls, *args, **kwargs)


def moved(modpath, objname):
    return _defaultdeprecator.moved(None, modpath, objname)


moved.__doc__ = _defaultdeprecator.moved.__doc__


def attribute_renamed(old_name, new_name):
    """
    class decorator to allow getting backward compatibility for renamed attributes.

    >>> @attribute_renamed(old_name="old", new_name="new")
    ... class SomeClass:
    ...     def __init__(self):
    ...         self.new = 42

    >>> some_class = SomeClass()
    >>> print(some_class.old)
    sample.py:15: DeprecationWarning: SomeClass.old has been renamed and is deprecated, use SomeClass.new instead
      print(some_class.old)
    42
    >>> some_class.old = 43
    sample.py:16: DeprecationWarning: SomeClass.old has been renamed and is deprecated, use SomeClass.new instead
      some_class.old = 43
    >>> some_class.old == some_class.new
    True
    """
    def _class_wrap(klass):
        reason = (
            f"{klass.__name__}.{old_name} has been renamed and is deprecated, use "
            f"{klass.__name__}.{new_name} instead"
        )

        def _get_old(self):
            warn(reason, DeprecationWarning, stacklevel=2)
            return getattr(self, new_name)

        def _set_old(self, value):
            warn(reason, DeprecationWarning, stacklevel=2)
            setattr(self, new_name, value)

        def _del_old(self):
            warn(reason, DeprecationWarning, stacklevel=2)
            delattr(self, new_name)

        setattr(klass, old_name, property(_get_old, _set_old, _del_old))

        return klass

    return _class_wrap


def argument_renamed(old_name, new_name):
    """
    callable decorator to allow getting backward compatibility for renamed keyword arguments.

    >>> @argument_renamed(old_name="old", new_name="new")
    ... def some_function(new):
    ...     return new
    >>> some_function(old=42)
    sample.py:15: DeprecationWarning: argument old of callable some_function has been renamed and is deprecated, use keyword argument new instead
      some_function(old=42)
    42
    """
    def _wrap(func):
        @wraps(func)
        def check_kwargs(*args, **kwargs):
            if old_name in kwargs and new_name in kwargs:
                raise ValueError(f"argument {old_name} of callable {func.__name__} has been "
                                 f"renamed to {new_name} but you are both using {old_name} and "
                                 f"{new_name} has keyword arguments, only uses {new_name}")

            if old_name in kwargs:
                warn(f"argument {old_name} of callable {func.__name__} has been renamed and is "
                     f"deprecated, use keyword argument {new_name} instead", stacklevel=2)
                kwargs[new_name] = kwargs[old_name]
                del kwargs[old_name]

            return func(*args, **kwargs)

        return check_kwargs

    return _wrap


def renamed(old_name, new_function):
    """use to tell that a callable has been renamed.

    It returns a callable wrapper, so that when its called a warning is printed
    telling what is the object new name.

    >>> old_function = renamed('old_function', new_function)
    >>> old_function()
    sample.py:57: DeprecationWarning: old_function has been renamed and is deprecated, uses new_function instead
    old_function()
    >>>
    """
    return _defaultdeprecator.renamed(old_name, new_function)


def class_renamed(old_name, new_class, message=None):
    """automatically creates a class which fires a DeprecationWarning
    when instantiated.

    >>> Set = class_renamed('Set', set, 'Set is now replaced by set')
    >>> s = Set()
    sample.py:57: DeprecationWarning: Set is now replaced by set
    s = Set()
    >>>
    """
    return _defaultdeprecator.class_renamed(None, old_name, new_class, message)

def class_moved(new_class, old_name=None, message=None):
    return _defaultdeprecator.class_moved(None, new_class, old_name, message)
class_moved.__doc__ = _defaultdeprecator.class_moved.__doc__