Created
April 9, 2020 13:14
-
-
Save timofurrer/5c26f51bbd3ca4be41862768361481aa to your computer and use it in GitHub Desktop.
Python Module to mark enum members as deprecated
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from enum import Enum, EnumMeta, auto | |
import warnings | |
class deprecated: | |
"""object to mark an enum member as deprecated | |
This marker works much like the `enum.auto()`. | |
At the moment only `Enum`s based on `object` work, | |
e.g. `IntEnum` doesn't work. | |
""" | |
value = object() | |
def __init__(self, deprecation_msg_tpl=None): | |
if deprecation_msg_tpl is None: | |
deprecation_msg_tpl = ( | |
"The enum member {attr} is deprecated " | |
"and will be removed in the future" | |
) | |
self._deprecation_msg_tpl = deprecation_msg_tpl | |
def __repr__(self): | |
return self._deprecation_msg_tpl | |
class allow_deprecation(EnumMeta): | |
"""Metaclass to properly handle the access to `deprecated` enum members""" | |
def __getattribute__(cls, name): | |
attr = type.__getattribute__(cls, name) | |
if hasattr(attr, "value") and isinstance(attr.value, deprecated): | |
warnings.warn( | |
repr(attr).format(attr=attr.name), | |
DeprecationWarning, stacklevel=2 | |
) | |
return attr | |
class MyEnum(Enum, metaclass=allow_deprecation): | |
FOO = auto() | |
BAR = deprecated() | |
MEH = auto() | |
BAR2 = deprecated("The enum member {attr} will be removed tomorrow") | |
if __name__ == "__main__": | |
warnings.simplefilter("default") | |
print("FOO", MyEnum.FOO, MyEnum.FOO.value) | |
print("BAR", MyEnum.BAR, MyEnum.BAR.value) | |
print("MEH", MyEnum.MEH, MyEnum.MEH.value) | |
print("BAR", MyEnum.BAR, MyEnum.BAR.value) | |
print("BAR2", MyEnum.BAR2, MyEnum.BAR2.value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment