Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What kind of exception to raise for unknown enum value?

Assume the following class:

class PersistenceType(enum.Enum):
  keyring = 1
  file = 2

  def __str__(self):
    type2String = {PersistenceType.keyring: "keyring", PersistenceType.file: "file"}
    return type2String[self]

  @staticmethod
  def from_string(type):
    if (type == "keyring" ):
        return PersistenceType.keyring
    if (type == "file"):
        return PersistenceType.file
    raise ???

Being a python noob, I am simply wondering: what specific kind of exception should be raised here?

like image 524
GhostCat Avatar asked Mar 10 '23 10:03

GhostCat


1 Answers

The short answer is ValueError:

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

The longer answer is that almost none of that class should exist. Consider:

class PersistenceType(enum.Enum):
    keyring = 1
    file = 2

This gives you everything your customized enum does:

  • To get the same result as your customised __str__ method, just use the name property:

    >>> PersistenceType.keyring.name
    'keyring'
    
  • To get a member of the enum using its name, treat the enum as a dict:

    >>> PersistenceType['keyring']
    <PersistenceType.keyring: 1>
    

Using the built-in abilities of Enum.enum gives you several advantages:

  1. You're writing much less code.

  2. You aren't repeating the names of the enum members all over the place, so you aren't going to miss anything if you modify it at some point.

  3. Users of your enum, and readers of code that uses it, don't need to remember or look up any customized methods.

If you're coming to Python from Java, it's always worth bearing in mind that:

Python Is Not Java (or, stop writing so much code)

Guido1 has a time machine (or, stop writing so much code)


1 … or in this case Ethan Furman, the author of the enum module.

like image 161
Zero Piraeus Avatar answered Mar 16 '23 21:03

Zero Piraeus