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?
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:
You're writing much less code.
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.
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.
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