Given the following enum:
class MyEnum(enum.Enum):
Field1 = "Field1"
Field2 = "Field2" # should be deprecated for `Field3`
Filed3 = "Field3"
I'd like to add a deprecation warning to a field such that when I call MyEnum.Field2 or MyEnum("Field2") a <MyEnum.Field3: 'Field3'> enum instance will be returned as well as a deprecation warning.
What is the proper way to do so? Is there a python language feature that can do this?
So far, I only managed to add a custom deprecation warning for the case MyEnum("Field2") (but not for MyEnum.Field2) by overloading the _missing_ method as follows:
import enum
class MyEnum(enum.Enum):
@classmethod
def _missing_(cls, value: object):
"""Add deprecation warningt to Field2"""
if str(value) == "Field2":
print("Field name `Field2` for `MyEnum` enum is deprecated.")
return cls.Field3
return value
Field1 = "Field1"
# Field2 = "Field2" # should be deprecated
Field3 = "Field3"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With