python - What kind of exception to raise for unknown enum value? -


assume 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 python noob, wondering: specific kind of exception should raised here?

the short answer valueerror:

raised when built-in operation or function receives argument has right type inappropriate value, , situation not described more precise exception such indexerror.

the longer answer none of class should exist. consider:

class persistencetype(enum.enum):     keyring = 1     file = 2 

this gives customized enum does:

  • to same result customised __str__ method, use name property:

    >>> persistencetype.keyring.name 'keyring' 
  • to member of enum using name, treat enum dict:

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

using built-in abilities of enum.enum gives several advantages:

  1. you're writing less code.

  2. you aren't repeating names of enum members on place, aren't going miss if modify @ point.

  3. users of enum, , readers of code uses it, don't need remember or customized methods.

if you're coming python java, it's worth bearing in mind that:

python not java (or, stop writing code)

guido1 has time machine (or, stop writing code)


1 … or in case ethan furman, author of enum module.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -