Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Assigning a default value to an enum class when the value provided to the constructor is not enumerated

I have an enum class:

import enum

class Version(enum.IntEnum):
    VERSION_1 = 1
    VERSION_2 = 2
    VERSION_UNKNOWN = 99

When a user initializes the enum class with a value that is not listed as a class field, I would like him to get VERSION_UNKNOWN i.e. the following snippet to execute successfully:

e = enum(3)
assert e == Version.VERSION_UNKNOWN

Is there any way to do that sort of thing?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

i think the enum build-in _missing_ is your friend: https://docs.python.org/3/library/enum.html#enum.Enum._missing_

import enum

class Version(enum.IntEnum):
    VERSION_1 = 1
    VERSION_2 = 2
    VERSION_UNKNOWN = 99

    @classmethod
    def _missing_(cls, value):
        return Version.VERSION_UNKNOWN
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading