Coverage for /home/jenkins/workspace/NDS/Zserio/NDS_ZSERIO-linux-build/compiler/extensions/python/runtime/src/zserio/enum.py: 100%
28 statements
« prev ^ index » next coverage.py v6.5.0, created at 2023-12-13 15:12 +0000
« prev ^ index » next coverage.py v6.5.0, created at 2023-12-13 15:12 +0000
1"""
2The module provides custom zserio Enum which allows to mark enum items deprecated.
3"""
5import enum
6import typing
7import warnings
9class _EnumType(enum.EnumMeta):
10 """
11 Special enum meta class which fires a warning whenever a deprecated enum item is accessed.
12 """
14 def __getattribute__(cls, name):
15 obj = super().__getattribute__(name)
16 if isinstance(obj, enum.Enum) and obj._is_deprecated:
17 warnings.warn(DeprecationWarning(f"Enum item '{obj}' is deprecated!"), stacklevel=2)
18 return obj
20 def __getitem__(cls, name):
21 member = super().__getitem__(name)
22 if member._is_deprecated:
23 warnings.warn(DeprecationWarning(f"Enum item '{member}' is deprecated!"), stacklevel=2)
24 return member
26 def __call__(cls, value, names=None, *, module=None, qualname=None, type_=None, start=1):
27 obj = super().__call__(value, names, module=module, qualname=qualname, type=type_, start=start)
28 if isinstance(obj, enum.Enum) and obj._is_deprecated:
29 warnings.warn(DeprecationWarning(f"Enum item '{obj}' is deprecated!"), stacklevel=2)
30 return obj
32class DeprecatedItem:
33 """
34 Marker used to make enum items deprecated.
36 Just use the class instead of creating an instance.
38 Example:
40 .. code:: python
42 import zserio
44 class MyEnum(zserio.Enum):
45 STABLE = 1,
46 OLD = 2, zserio.DeprecatedItem
47 NEW = 3
48 """
50class Enum(enum.Enum, metaclass=_EnumType):
51 """
52 Custom zserio enum base class which allows to mark items deprecated.
53 """
55 def __new__(cls, value: typing.Any , deprecated: typing.Optional[DeprecatedItem] = None):
56 """
57 Creator method which allows to mark the item as deprecated.
59 :param value: The enum item value.
60 :param deprecated: DeprecatedItem or None.
62 :returns: Instance of the enum item.
63 """
65 member = object.__new__(cls)
66 member._value_ = value
67 if deprecated is not None and deprecated != DeprecatedItem:
68 raise ValueError(f"Invalid argument 'deprecated', which is {deprecated}! "
69 f"Expecting {DeprecatedItem} or None.")
70 member._is_deprecated = deprecated is not None # type: ignore[attr-defined]
71 return member