Enumerated type. Each instance of this class represents an enumerated type. The values of the type must be declared *exhaustively* and named with *strings*, and they might be given explicit concrete values, though this is not compulsory. Once the type is defined, it can not
| 26 | |
| 27 | |
| 28 | class Enum: |
| 29 | """Enumerated type. |
| 30 | |
| 31 | Each instance of this class represents an enumerated type. The |
| 32 | values of the type must be declared |
| 33 | *exhaustively* and named with |
| 34 | *strings*, and they might be given explicit |
| 35 | concrete values, though this is not compulsory. Once the type is |
| 36 | defined, it can not be modified. |
| 37 | |
| 38 | There are three ways of defining an enumerated type. Each one |
| 39 | of them corresponds to the type of the only argument in the |
| 40 | constructor of Enum: |
| 41 | |
| 42 | - *Sequence of names*: each enumerated |
| 43 | value is named using a string, and its order is determined by |
| 44 | its position in the sequence; the concrete value is assigned |
| 45 | automatically:: |
| 46 | |
| 47 | >>> boolEnum = Enum(['True', 'False']) |
| 48 | |
| 49 | - *Mapping of names*: each enumerated |
| 50 | value is named by a string and given an explicit concrete value. |
| 51 | All of the concrete values must be different, or a |
| 52 | ValueError will be raised:: |
| 53 | |
| 54 | >>> priority = Enum({'red': 20, 'orange': 10, 'green': 0}) |
| 55 | >>> colors = Enum({'red': 1, 'blue': 1}) |
| 56 | Traceback (most recent call last): |
| 57 | ... |
| 58 | ValueError: enumerated values contain duplicate concrete values: 1 |
| 59 | |
| 60 | - *Enumerated type*: in that case, a copy |
| 61 | of the original enumerated type is created. Both enumerated |
| 62 | types are considered equal:: |
| 63 | |
| 64 | >>> prio2 = Enum(priority) |
| 65 | >>> priority == prio2 |
| 66 | True |
| 67 | |
| 68 | Please note that names starting with _ are |
| 69 | not allowed, since they are reserved for internal usage:: |
| 70 | |
| 71 | >>> prio2 = Enum(['_xx']) |
| 72 | Traceback (most recent call last): |
| 73 | ... |
| 74 | ValueError: name of enumerated value can not start with ``_``: '_xx' |
| 75 | |
| 76 | The concrete value of an enumerated value is obtained by |
| 77 | getting its name as an attribute of the Enum |
| 78 | instance (see __getattr__()) or as an item (see |
| 79 | __getitem__()). This allows comparisons between |
| 80 | enumerated values and assigning them to ordinary Python |
| 81 | variables:: |
| 82 | |
| 83 | >>> redv = priority.red |
| 84 | >>> redv == priority['red'] |
| 85 | True |