2

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?

wueli
  • 951
  • 11
  • 19
  • Seems to have been solved here: https://stackoverflow.com/questions/62299740/how-do-i-detect-and-invoke-a-function-when-a-python-enum-member-is-accessed – HerrIvan Oct 20 '22 at 08:51

1 Answers1

0

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"
wueli
  • 951
  • 11
  • 19