PN07815
PN07815

Reputation: 123

Confused with using Python Enum while implementing a class

This is the first time I'm working with Enum and would appreciate any help with the code below. As per my understanding when you define an Enum class with a set of values/names, any field/variable of that particular Enum type can't have values/names not in the Enum class.

Suppose I have to create an Allergy class which has a field for "severity" that can have values "LOW, MEDIUM, HIGH" and I have to represent this using enum. I thought if the input for "severity" while creating an object has a value other than LOW, MEDIUM or HIGH, the program would raise an error. Is that correct or should I explicitly check that the input is present in the enum class before setting/initializing "severity" ? If we have to explicitly check then what's the purpose of using Enum?


from enum import Enum,auto

class Severity(Enum):
    LOW = auto()
    MEDIUM = auto()
    HIGH = auto()

class Allergy:
    def __init__(self, name, symptoms, reporter, severity:Severity):
        self.__name = name
        self.__reporter = reporter        
        self.__symptoms = symptoms
        self.__severity = severity

     def get_severity(self):
        return self.__severity

     def set_severity(self, severity:Severity):
        self.__severity = severity

allergy = Allergy("Dust Allergy","sneezes","Doctor", "5")
print("How severe is the allergy? ",allergy.get_severity())


I was expecting the code to raise an error or not run as "5" is not in the Enum class. But this is the output

How severe is the allergy?  5

I'm not sure if I'm missing something very basic here but none of the examples online seem to clear my doubts. All of the examples that I have seen so far show the basic syntax/how to directly access names in the Enum class but not how to use this in a different class.

Thanks.

Upvotes: 1

Views: 201

Answers (1)

Karan Shishoo
Karan Shishoo

Reputation: 2857

A couple of things, as blhsing mentioned in his comment, your use of type hints are not automatically enforced in python. Secondly you never use the Severity Enum that you made in your code to check for validity, you could change the initialization to-

class Allergy:
    def __init__(self, name, symptoms, reporter, severity:Severity):
        self.__name = name
        self.__reporter = reporter        
        self.__symptoms = symptoms
        self.__severity = Severity[severity]

This now attempts to save the corresponding severity of the enum using the name provided. In the case of the name not existing in the Enum it will throw a NameError as you were previously expecting.

*Note you need to change your set_severity function in a similar manner as well

Upvotes: 1

Related Questions