Ticket #2245: properties.py

File properties.py, 1.7 KB (added by Peaker, 7 years ago)
Line 
1import warnings
2
3def deprecated_property(warning_text, getter=None, setter=None, deller=None, doc=None):
4    """Create a property that uses the given getter/setter/deller/doc,
5    but wraps them with a deprecation warning of the given text.
6
7    Note that setters/dellers are only usable with new-style classes."""
8    getattr_with_deprecation = setattr_with_deprecation = detattr_with_deprecation = None
9    if getter:
10        def getattr_with_deprecation(self):
11            warnings.warn(warning_text, DeprecationWarning, stacklevel=2)
12            return getter(self)
13    if setter:
14        def setattr_with_deprecation(self, new_value):
15            warnings.warn(warning_text, DeprecationWarning, stacklevel=2)
16            setter(self, new_value)
17    if deller:
18        def detattr_with_deprecation(self):
19            warnings.warn(warning_text, DeprecationWarning, stacklevel=2)
20            deller(self)
21    return property(getattr_with_deprecation,
22                    setattr_with_deprecation,
23                    detattr_with_deprecation, doc)
24
25def deprecated_attribute(warning_text, name, getter=False, setter=False, deller=False, doc=None):
26    getattr_by_name = setattr_by_name = delattr_by_name = None
27    if getter:
28        def getattr_by_name(self):
29            return getattr(self, name)
30    if setter:
31        def setattr_by_name(self, value):
32            setattr(self, name, value)
33    if deller:
34        def delattr_by_name(self):
35            delattr(self, name)
36    return deprecated_property(warning_text,
37                               getattr_by_name,
38                               setattr_by_name,
39                               delattr_by_name,
40                               doc)