1 | \chapter{Related Work} |
---|
2 | \label{s:RelatedWork} |
---|
3 | |
---|
4 | \begin{comment} |
---|
5 | An algebraic data type (ADT) can be viewed as a recursive sum of product types. |
---|
6 | A sum type lists values as members. |
---|
7 | A member in a sum type definition is known as a data constructor. |
---|
8 | For example, C supports sum types union and enumeration (enum). |
---|
9 | An enumeration in C can be viewed as the creation of a list of zero-arity data constructors. |
---|
10 | A union instance holds a value of one of its member types. |
---|
11 | Defining a union does not generate new constructors. |
---|
12 | The definition of member types and their constructors are from the outer lexical scope. |
---|
13 | |
---|
14 | In general, an \Newterm{algebraic data type} (ADT) is a composite type, \ie, a type formed by combining other types. |
---|
15 | Three common classes of algebraic types are \Newterm{array type}, \ie homogeneous types, \Newterm{product type}, \ie heterogeneous tuples and records (structures), and \Newterm{sum type}, \ie tagged product-types (unions). |
---|
16 | Enumerated types are a special case of product/sum types with non-mutable fields, \ie initialized (constructed) once at the type's declaration, possible restricted to compile-time initialization. |
---|
17 | Values of algebraic types are access by subscripting, field qualification, or type (pattern) matching. |
---|
18 | \end{comment} |
---|
19 | |
---|
20 | Enumeration types exist in many popular programming languages, both past and present, \eg Pascal~\cite{Pascal}, Ada~\cite{Ada}, \Csharp~\cite{Csharp}, OCaml~\cite{OCaml} \CC, Go~\cite{Go}, Java~\cite{Java}, Modula-3~\cite{Modula-3}, Rust~\cite{Rust}, Swift~\cite{Swift}, Python~\cite{Python}. |
---|
21 | Among theses languages, there are a large set of overlapping features, but each language has its own unique extensions and restrictions. |
---|
22 | |
---|
23 | \section{Pascal} |
---|
24 | \label{s:Pascal} |
---|
25 | \lstnewenvironment{pascal}[1][]{\lstset{language=pascal,escapechar=\$,moredelim=**[is][\color{red}]{@}{@},}\lstset{#1}}{} |
---|
26 | |
---|
27 | Classic Pascal has the \lstinline[language=pascal]{const} declaration binding a name to a constant literal/expression. |
---|
28 | \begin{pascal} |
---|
29 | const one = 0 + 1; Vowels = set of (A,E,I,O,U); NULL = NIL; |
---|
30 | PI = 3.14159; Plus = '+'; Fred = 'Fred'; |
---|
31 | \end{pascal} |
---|
32 | This mechanism is not an enumeration because there is no specific type (pseudo enumeration). |
---|
33 | Hence, there is no notion of a (possibly ordered) set, modulo the \lstinline[language=pascal]{set of} type. |
---|
34 | The type of each constant name (enumerator) is inferred from the constant-expression type. |
---|
35 | |
---|
36 | Free Pascal~\cite[\S~3.1.1]{FreePascal} is a modern, object-oriented version of classic Pascal, with a C-style enumeration type. |
---|
37 | Enumerators must be assigned in ascending numerical order with a constant expression and the range can be non-consecutive. |
---|
38 | \begin{pascal} |
---|
39 | Type EnumType = ( one, two, three, forty @= 40@, fortyone ); |
---|
40 | \end{pascal} |
---|
41 | Pseudo-functions @Pred@ and @Succ@ can only be used if the range is consecutive. |
---|
42 | The underlying type is an implementation-defined integral-type large enough to hold all enumerated values; it does not have to be the smallest possible type. |
---|
43 | The integral size can be explicitly specified using compiler directive @$PACKENUM@~$N$, where $N$ is the number of bytes, \eg: |
---|
44 | \begin{pascal} |
---|
45 | Type @{$\color{red}\$$PACKENUM 1}@ SmallEnum = ( one, two, three ); |
---|
46 | @{$\color{red}\$$PACKENUM 4}@ LargeEnum = ( BigOne, BigTwo, BigThree ); |
---|
47 | Var S : SmallEnum; { 1 byte } |
---|
48 | L : LargeEnum; { 4 bytes} |
---|
49 | \end{pascal} |
---|
50 | |
---|
51 | |
---|
52 | \section{Ada} |
---|
53 | \lstnewenvironment{ada}[1][]{\lstset{language=[2005]Ada,escapechar=\$,moredelim=**[is][\color{red}]{@}{@},literate={'}{\ttfamily'\!}1}\lstset{#1}}{} |
---|
54 | |
---|
55 | An Ada enumeration type is an ordered list of constants, called \Newterm{literals} (enumerators). |
---|
56 | \begin{ada} |
---|
57 | type RGB is ( Red, Green, Blue ); -- 3 literals (enumerators) |
---|
58 | \end{ada} |
---|
59 | Object initialization and assignment are restricted to the enumerators of this type. |
---|
60 | Enumerators without an explicitly designated constant value are auto-initialized: from left to right, starting at zero or the next explicitly initialized constant, incrementing by 1. |
---|
61 | To explicitly set enumerator values, \emph{all} enumerators must be set in \emph{ascending} order, \ie there is no auto-initialization. |
---|
62 | \begin{ada} |
---|
63 | type RGB is ( Red, Green, Blue ); |
---|
64 | @for RGB use ( Red => 10, Green => 20, Blue => 30 );@ -- ascending order |
---|
65 | \end{ada} |
---|
66 | Hence, the position, value, label tuples are: |
---|
67 | \begin{ada} |
---|
68 | (0, 10, RED) (1, 20, GREEN) (2, 30, BLUE) |
---|
69 | \end{ada} |
---|
70 | Note, Ada is case-\emph{insensitive} so names may appear in multiple forms and still be the same, \eg @Red@ and @RED@ (a questionable design decision). |
---|
71 | |
---|
72 | Like C, Ada enumerators are unscoped, \ie enumerators declared inside of an enum are visible (projected) into the enclosing scope. |
---|
73 | The enumeration operators are the ordering operators, @=@, @<@, @<=@, @=@, @/=@, @>=@, @>@, where the ordering relationship is given implicitly by the sequence of enumerators, which is always ascending. |
---|
74 | |
---|
75 | Ada enumerators are overloadable. |
---|
76 | \begin{ada} |
---|
77 | type Traffic_Light is ( @Red@, Yellow, @Green@ ); |
---|
78 | \end{ada} |
---|
79 | Like \CFA, Ada uses an advanced type-resolution algorithm, including the left-hand side of assignment, to disambiguate among overloaded names. |
---|
80 | \VRef[Figure]{f:AdaEnumeration} shows how ambiguity is handled using a cast, \ie \lstinline[language=ada]{RGB'(Red)}. |
---|
81 | |
---|
82 | \begin{figure} |
---|
83 | \begin{ada} |
---|
84 | with Ada.Text_IO; use Ada.Text_IO; |
---|
85 | procedure test is |
---|
86 | type RGB is ( @Red@, Green, Blue ); |
---|
87 | type Traffic_Light is ( @Red@, Yellow, Green ); -- overload |
---|
88 | procedure @Red@( Colour : RGB ) is begin -- overload |
---|
89 | Put_Line( "Colour is " & RGB'Image( Colour ) ); |
---|
90 | end Red; |
---|
91 | procedure @Red@( TL : Traffic_Light ) is begin -- overload |
---|
92 | Put_Line( "Light is " & Traffic_Light'Image( TL ) ); |
---|
93 | end Red; |
---|
94 | begin |
---|
95 | @Red@( Blue ); -- RGB |
---|
96 | @Red@( Yellow ); -- Traffic_Light |
---|
97 | @Red@( @RGB'(Red)@ ); -- ambiguous without cast |
---|
98 | end test; |
---|
99 | \end{ada} |
---|
100 | \caption{Ada Enumeration Overload Resolution} |
---|
101 | \label{f:AdaEnumeration} |
---|
102 | \end{figure} |
---|
103 | |
---|
104 | Ada provides an alias mechanism, \lstinline[language=ada]{renames}, for aliasing types, which is useful to shorten package names. |
---|
105 | \begin{ada} |
---|
106 | OtherRed : RGB renames Red; |
---|
107 | \end{ada} |
---|
108 | which suggests a possible \CFA extension to @typedef@. |
---|
109 | \begin{cfa} |
---|
110 | typedef RGB.Red OtherRed; |
---|
111 | \end{cfa} |
---|
112 | |
---|
113 | There are three pairs of inverse enumeration pseudo-functions (attributes): @'Pos@ and @'Val@, @'Enum_Rep@ and @'Enum_Val@, and @'Image@ and @'Value@, |
---|
114 | \begin{cquote} |
---|
115 | \lstDeleteShortInline@ |
---|
116 | \setlength{\tabcolsep}{15pt} |
---|
117 | \begin{tabular}{@{}ll@{}} |
---|
118 | \begin{ada} |
---|
119 | RGB'Pos( Red ) = 0; |
---|
120 | RGB'Enum_Rep( Red ) = 10; |
---|
121 | RGB'Image( Red ) = "RED"; |
---|
122 | \end{ada} |
---|
123 | & |
---|
124 | \begin{ada} |
---|
125 | RGB'Val( 0 ) = Red |
---|
126 | RGB'Enum_Val( 10 ) = Red |
---|
127 | RGB'Value( "Red" ) = Red |
---|
128 | \end{ada} |
---|
129 | \end{tabular} |
---|
130 | \lstMakeShortInline@ |
---|
131 | \end{cquote} |
---|
132 | These attributes are important for IO. |
---|
133 | An enumeration type @T@ also has the following attributes: @T'First@, @T'Last@, @T'Range@, @T'Pred@, @T'Succ@, @T'Min@, and @T'Max@, producing an intuitive result based on the attribute name. |
---|
134 | |
---|
135 | Ada allows the enumerator label to be a character constant. |
---|
136 | \begin{ada} |
---|
137 | type Operator is ( '+', '-', '*', '/' ); |
---|
138 | \end{ada} |
---|
139 | which is syntactic sugar for the label and not character literals from the predefined type @Character@. |
---|
140 | The purpose is strictly readability using character literals rather than names. |
---|
141 | \begin{ada} |
---|
142 | Op : Operator := '+'; |
---|
143 | if Op = '+' or else Op = '-' then ... ; |
---|
144 | elsif Op = '*' or else Op = '/' then ... ; end if; |
---|
145 | \end{ada} |
---|
146 | Interestingly, arrays of character enumerators can be treated as strings. |
---|
147 | \begin{ada} |
---|
148 | Ops : array( 0..3 ) of Operator; |
---|
149 | Ops := @"+-*/"@; -- string assignment to array elements |
---|
150 | Ops := @"+-" & "*/"@; -- string concatenation and assignment |
---|
151 | \end{ada} |
---|
152 | Ada's @Character@ type is defined as a character enumeration across all Latin-1 characters. |
---|
153 | |
---|
154 | Ada's boolean type is also a special enumeration, which can be used in conditions. |
---|
155 | \begin{ada} |
---|
156 | type Boolean is (False, True); -- False / True not keywords |
---|
157 | @Flag@ : Boolean; |
---|
158 | if @Flag@ then ... -- conditional |
---|
159 | \end{ada} |
---|
160 | Since only types derived from @Boolean@ can be a conditional, @Boolean@ is essentially a builtin type. |
---|
161 | |
---|
162 | Ada provides \emph{consecutive} subtyping of an enumeration using \lstinline[language=ada]{range}. |
---|
163 | \begin{ada} |
---|
164 | type Week is ( Mon, Tue, Wed, Thu, Fri, Sat, Sun ); |
---|
165 | subtype Weekday is Week @range Mon .. Fri@; |
---|
166 | subtype Weekend is Week @range Sat .. Sun@; |
---|
167 | Day : Week; |
---|
168 | \end{ada} |
---|
169 | Hence, the ordering of the enumerators is crucial to provide the necessary ranges. |
---|
170 | |
---|
171 | An enumeration type can be used in the Ada \lstinline[language=ada]{case} (all enumerators must appear or a default) or iterating constructs. |
---|
172 | \begin{cquote} |
---|
173 | \lstDeleteShortInline@ |
---|
174 | \setlength{\tabcolsep}{15pt} |
---|
175 | \begin{tabular}{@{}ll@{}} |
---|
176 | \begin{ada} |
---|
177 | case Day is |
---|
178 | when @Mon .. Fri@ => ... ; |
---|
179 | when @Sat .. Sun@ => ... ; |
---|
180 | end case; |
---|
181 | \end{ada} |
---|
182 | & |
---|
183 | \begin{ada} |
---|
184 | case Day is |
---|
185 | when @Weekday@ => ... ; -- subtype ranges |
---|
186 | when @Weekend@ => ... ; |
---|
187 | end case; |
---|
188 | \end{ada} |
---|
189 | \end{tabular} |
---|
190 | \end{cquote} |
---|
191 | |
---|
192 | \begin{cquote} |
---|
193 | \setlength{\tabcolsep}{12pt} |
---|
194 | \begin{tabular}{@{}lll@{}} |
---|
195 | \begin{ada} |
---|
196 | for Day in @Mon .. Sun@ loop |
---|
197 | ... |
---|
198 | end loop; |
---|
199 | \end{ada} |
---|
200 | & |
---|
201 | \begin{ada} |
---|
202 | for Day in @Weekday@ loop |
---|
203 | ... |
---|
204 | end loop; |
---|
205 | \end{ada} |
---|
206 | & |
---|
207 | \begin{ada} |
---|
208 | for Day in @Weekend@ loop |
---|
209 | ... |
---|
210 | end loop; |
---|
211 | \end{ada} |
---|
212 | \end{tabular} |
---|
213 | \lstMakeShortInline@ |
---|
214 | \end{cquote} |
---|
215 | |
---|
216 | An enumeration type can be used as an array dimension and subscript. |
---|
217 | \begin{ada} |
---|
218 | Lunch : array( @Week@ ) of Time; |
---|
219 | for Day in Week loop |
---|
220 | Lunch( @Day@ ) := ... ; -- set lunch time |
---|
221 | end loop; |
---|
222 | \end{ada} |
---|
223 | |
---|
224 | |
---|
225 | \section{\CC} |
---|
226 | \label{s:C++RelatedWork} |
---|
227 | \lstnewenvironment{c++}[1][]{\lstset{language=[GNU]C++,escapechar=\$,moredelim=**[is][\color{red}]{@}{@},}\lstset{#1}}{} |
---|
228 | |
---|
229 | \CC has the equivalent of Pascal typed @const@ declarations \see{\VRef{s:Pascal}}, with static and dynamic initialization. |
---|
230 | \begin{c++} |
---|
231 | const auto one = 0 + 1; $\C{// static intialization}$ |
---|
232 | const auto NULL = nullptr; |
---|
233 | const auto PI = 3.14159; |
---|
234 | const auto Plus = '+'; |
---|
235 | const auto Fred = "Fred"; |
---|
236 | const auto Mon = 0, Tue = Mon + 1, Wed = Tue + 1, Thu = Wed + 1, Fri = Thu + 1, |
---|
237 | Sat = Fri + 1, Sun = Sat + 1; |
---|
238 | int sa[Sun]; |
---|
239 | const auto r = random(); $\C{// dynamic intialization}$ |
---|
240 | int da[r]; $\C{// VLA}$ |
---|
241 | \end{c++} |
---|
242 | Statically initialized identifiers may appear in any constant-expression context, \eg @case@. |
---|
243 | Dynamically intialized identifiers may appear as array dimensions in @g++@, which allows variable-sized arrays. |
---|
244 | Interestingly, global \CC @const@ declarations are implicitly marked @static@ (@r@ rather than @R@). |
---|
245 | \begin{c++} |
---|
246 | $\$$ nm test.o |
---|
247 | 0000000000000018 @r@ Mon |
---|
248 | \end{c++} |
---|
249 | |
---|
250 | \CC enumeration is largely backwards compatible with C, so it inherited C's enumerations. |
---|
251 | However, the following non-backwards compatible changes are made. |
---|
252 | |
---|
253 | \begin{cquote} |
---|
254 | 7.2 Change: \CC objects of enumeration type can only be assigned values of the same enumeration type. |
---|
255 | In C, objects of enumeration type can be assigned values of any integral type. \\ |
---|
256 | Example: |
---|
257 | \begin{c++} |
---|
258 | enum color { red, blue, green }; |
---|
259 | color c = 1; $\C{// valid C, invalid C++}$ |
---|
260 | \end{c++} |
---|
261 | \textbf{Rationale}: The type-safe nature of \CC. \\ |
---|
262 | \textbf{Effect on original feature}: Deletion of semantically well-defined feature. \\ |
---|
263 | \textbf{Difficulty of converting}: Syntactic transformation. (The type error produced by the assignment can be automatically corrected by applying an explicit cast.) \\ |
---|
264 | \textbf{How widely used}: Common. |
---|
265 | \end{cquote} |
---|
266 | |
---|
267 | \begin{cquote} |
---|
268 | 7.2 Change: In \CC, the type of an enumerator is its enumeration. |
---|
269 | In C, the type of an enumerator is @int@. \\ |
---|
270 | Example: |
---|
271 | \begin{c++} |
---|
272 | enum e { A }; |
---|
273 | sizeof(A) == sizeof(int) $\C{// in C}$ |
---|
274 | sizeof(A) == sizeof(e) $\C{// in C++}$ |
---|
275 | /* and sizeof(int) is not necessary equal to sizeof(e) */ |
---|
276 | \end{c++} |
---|
277 | \textbf{Rationale}: In \CC, an enumeration is a distinct type. \\ |
---|
278 | \textbf{Effect on original feature}: Change to semantics of well-defined feature. \\ |
---|
279 | \textbf{Difficulty of converting}: Semantic transformation. \\ |
---|
280 | \textbf{How widely used}: Seldom. The only time this affects existing C code is when the size of an enumerator is taken. |
---|
281 | Taking the size of an enumerator is not a common C coding practice. |
---|
282 | \end{cquote} |
---|
283 | |
---|
284 | Hence, the values in a \CC enumeration can only be its enumerators (without a cast). |
---|
285 | While the storage size of an enumerator is up to the compiler, there is still an implicit cast to @int@. |
---|
286 | \begin{c++} |
---|
287 | enum E { A, B, C }; |
---|
288 | E e = A; |
---|
289 | int i = A; i = e; $\C{// implicit casts to int}$ |
---|
290 | \end{c++} |
---|
291 | \CC{11} added a scoped enumeration, \lstinline[language=c++]{enum class} (or \lstinline[language=c++]{enum struct}), where the enumerators are accessed using type qualification. |
---|
292 | \begin{c++} |
---|
293 | enum class E { A, B, C }; |
---|
294 | E e = @E::@A; $\C{// qualified enumerator}$ |
---|
295 | e = B; $\C{// error: B not in scope}$ |
---|
296 | \end{c++} |
---|
297 | \CC{20} supports explicit unscoping with a \lstinline[language=c++]{using enum} declaration. |
---|
298 | \begin{c++} |
---|
299 | enum class E { A, B, C }; |
---|
300 | @using enum E;@ |
---|
301 | E e = A; e = B; $\C{// direct access}$ |
---|
302 | \end{c++} |
---|
303 | \CC{11} added the ability to explicitly declare the underlying \emph{integral} type for \lstinline[language=c++]{enum class}. |
---|
304 | \begin{c++} |
---|
305 | enum class RGB @: long@ { Red, Green, Blue }; |
---|
306 | enum class rgb @: char@ { Red = 'r', Green = 'g', Blue = 'b' }; |
---|
307 | enum class srgb @: signed char@ { Red = -1, Green = 0, Blue = 1 }; |
---|
308 | \end{c++} |
---|
309 | There is no implicit conversion from the \lstinline[language=c++]{enum class} type to its declared type. |
---|
310 | \begin{c++} |
---|
311 | rgb crgb = rgb::Red; |
---|
312 | char ch = rgb::Red; ch = crgb; $\C{// error}$ |
---|
313 | \end{c++} |
---|
314 | Finally, enumerations can be used in the @switch@ statement but there is no mechanism to iterate through an enumeration. |
---|
315 | An enumeration type cannot declare an array dimension but can be used as a subscript. |
---|
316 | There is no mechanism to subtype or inherit from enumerations. |
---|
317 | |
---|
318 | |
---|
319 | \section{C\raisebox{-0.7ex}{\LARGE$^\sharp$}\xspace} % latex bug: cannot use \relsize{2} so use \LARGE |
---|
320 | \label{s:Csharp} |
---|
321 | \lstnewenvironment{csharp}[1][]{\lstset{language=[Sharp]C,escapechar=\$,moredelim=**[is][\color{red}]{@}{@},}\lstset{#1}}{} |
---|
322 | |
---|
323 | % https://www.tutorialsteacher.com/codeeditor?cid=cs-mk8Ojx |
---|
324 | |
---|
325 | \Csharp is a dynamically-typed programming-language with a scoped, integral enumeration-type similar to the C/\CC enumeration. |
---|
326 | \begin{csharp} |
---|
327 | enum Weekday : byte { Mon, Tue, Wed, Thu@ = 10@, Fri, Sat, Sun@,@ }; |
---|
328 | \end{csharp} |
---|
329 | The default underlying type is @int@, with auto-incrementing, implicit/explicit initialization, terminator comma, and optional integral typing (default @int@). |
---|
330 | A method cannot be defined in an enumeration type. |
---|
331 | As well, there is an explicit bidirectional conversion between an enumeration and its integral type, and an implicit conversion to the enumerator label in display contexts. |
---|
332 | \begin{csharp} |
---|
333 | int day = (int)Weekday.Fri; $\C{// day == 10}$ |
---|
334 | Weekday weekday = (Weekdays)42; $\C{// weekday == 42, logically invalid}$ |
---|
335 | Console.WriteLine( Weekday.Fri ); $\C{// print Fri}$ |
---|
336 | string mon = Weekday.Mon.ToString(); $\C{// mon == "Mon"}$ |
---|
337 | \end{csharp} |
---|
338 | |
---|
339 | The @Enum.GetValues@ pseudo-method retrieves an array of the enumeration constants for looping over an enumeration type or variable (expensive operation). |
---|
340 | \begin{csharp} |
---|
341 | foreach ( Weekday constant in @Enum.GetValues@( typeof(Weekday) ) ) { |
---|
342 | Console.WriteLine( constant + " " + (int)constant ); // label, position |
---|
343 | } |
---|
344 | \end{csharp} |
---|
345 | |
---|
346 | The @Flags@ attribute creates a bit-flags enumeration, allowing bitwise operators @&@, @|@, @~@ (complement), @^@ (xor). |
---|
347 | \begin{csharp} |
---|
348 | @[Flags]@ public enum Weekday { |
---|
349 | None = 0x0, Mon = 0x1, Tue = 0x2, Wed = 0x4, |
---|
350 | Thu = 0x8, Fri = 0x10, Sat = 0x20, Sun = 0x40, |
---|
351 | Weekend = @Sat | Sun@, |
---|
352 | Weekdays = @Mon | Tue | Wed | Thu | Fri@ |
---|
353 | } |
---|
354 | Weekday meetings = @Weekday.Mon | Weekday.Wed@; // 0x5 |
---|
355 | \end{csharp} |
---|
356 | |
---|
357 | \VRef[Figure]{CsharpFreeVersusClass} shows an enumeration with free routines for manipulation, and embedding the enumeration and operations into an enumeration class. |
---|
358 | The key observation is that an enumeration class is just a structuring mechanism without any additional semantics. |
---|
359 | |
---|
360 | % https://learn.microsoft.com/en-us/dotnet/api/system.enum?view=net-8.0 |
---|
361 | |
---|
362 | \begin{figure} |
---|
363 | \centering |
---|
364 | \lstDeleteShortInline@ |
---|
365 | \begin{tabular}{@{}l|l@{}} |
---|
366 | \multicolumn{1}{@{}c|}{non-object oriented} & \multicolumn{1}{c@{}}{object oriented} \\ |
---|
367 | \hline |
---|
368 | \begin{csharp} |
---|
369 | public class Program { |
---|
370 | |
---|
371 | enum Weekday { |
---|
372 | Mon, Tue, Wed, Thu, Fri, Sat, Sun }; |
---|
373 | |
---|
374 | static bool isWeekday( Weekday wd ) { |
---|
375 | return wd <= Weekday.Fri; |
---|
376 | } |
---|
377 | static bool isWeekend( Weekday wd ) { |
---|
378 | return Weekday.Sat <= wd; |
---|
379 | } |
---|
380 | |
---|
381 | |
---|
382 | public static void Main() { |
---|
383 | Weekday day = Weekday.Sat; |
---|
384 | |
---|
385 | Console.WriteLine( isWeekday( day ) ); |
---|
386 | Console.WriteLine( isWeekend( day ) ); |
---|
387 | } |
---|
388 | } |
---|
389 | \end{csharp} |
---|
390 | & |
---|
391 | \begin{csharp} |
---|
392 | public class Program { |
---|
393 | public @class@ WeekDay : Enumeration { |
---|
394 | public enum Day { |
---|
395 | Mon, Tue, Wed, Thu, Fri, Sat, Sun }; |
---|
396 | public enum Day2 : Day { |
---|
397 | XXX, YYY }; |
---|
398 | Day day; |
---|
399 | public bool isWeekday() { |
---|
400 | return day <= Day.Fri; |
---|
401 | } |
---|
402 | public bool isWeekend() { |
---|
403 | return day > Day.Fri; |
---|
404 | } |
---|
405 | public WeekDay( Day d ) { day = d; } |
---|
406 | } |
---|
407 | public static void Main() { |
---|
408 | WeekDay cday = new |
---|
409 | WeekDay( WeekDay.Day.Sat ); |
---|
410 | Console.WriteLine( cday.isWeekday() ); |
---|
411 | Console.WriteLine( cday.isWeekend() ); |
---|
412 | } |
---|
413 | } |
---|
414 | \end{csharp} |
---|
415 | \end{tabular} |
---|
416 | \lstMakeShortInline@ |
---|
417 | \caption{\Csharp: Free Routine Versus Class Enumeration} |
---|
418 | \label{CsharpFreeVersusClass} |
---|
419 | \end{figure} |
---|
420 | |
---|
421 | |
---|
422 | \section{Golang} |
---|
423 | \lstnewenvironment{Go}[1][]{\lstset{language=Go,escapechar=\$,moredelim=**[is][\color{red}]{@}{@},}\lstset{#1}}{} |
---|
424 | |
---|
425 | Golang provides pseudo-enumeration similar to classic Pascal \lstinline[language=pascal]{const}, binding a name to a constant literal/expression. |
---|
426 | \begin{Go} |
---|
427 | const ( R = 0; G; B ) $\C{// implicit: 0 0 0}$ |
---|
428 | const ( Fred = "Fred"; Mary = "Mary"; Jane = "Jane" ) $\C{// explicit: Fred Mary Jane}$ |
---|
429 | const ( S = 0; T; USA = "USA"; U; V = 3.1; W ) $\C{// type change, implicit/explicit: 0 0 USA USA 3.1 3.1}$ |
---|
430 | \end{Go} |
---|
431 | Constant names are unscoped and must be unique (no overloading). |
---|
432 | The first enumerator \emph{must} be explicitly initialized; |
---|
433 | subsequent enumerators can be implicitly or explicitly initialized. |
---|
434 | Implicit initialization is the previous (predecessor) enumerator value. |
---|
435 | |
---|
436 | Auto-incrementing is supported by the keyword \lstinline[language=Go]{iota}, available only in the \lstinline[language=Go]{const} declaration. |
---|
437 | The \lstinline[language=Go]{iota} is a \emph{per \lstinline[language=golang]{const} declaration} integer counter, starting at zero and implicitly incremented by one for each \lstinline[language=golang]{const} identifier (enumerator). |
---|
438 | \begin{Go} |
---|
439 | const ( R = @iota@; G; B ) $\C{// implicit: 0 1 2}$ |
---|
440 | const ( C = @iota + B + 1@; G; Y ) $\C{// implicit: 3 4 5}$ |
---|
441 | \end{Go} |
---|
442 | An underscore \lstinline[language=golang]{const} identifier advances \lstinline[language=Go]{iota}. |
---|
443 | \begin{Go} |
---|
444 | const ( O1 = iota + 1; @_@; O3; @_@; O5 ) // 1, 3, 5 |
---|
445 | \end{Go} |
---|
446 | Auto-incrementing stops after an explicit initialization. |
---|
447 | \begin{Go} |
---|
448 | const ( Mon = iota; Tue; Wed; // 0, 1, 2 |
---|
449 | @Thu = 10@; Fri; Sat; Sun ) // 10, 10, 10, 10 |
---|
450 | \end{Go} |
---|
451 | Auto-incrementing can be restarted with an expression containing \emph{one} \lstinline[language=Go]{iota}. |
---|
452 | \begin{Go} |
---|
453 | const ( V1 = iota; V2; @V3 = 7;@ V4 = @iota@; V5 ) // 0 1 7 3 4 |
---|
454 | const ( Mon = iota; Tue; Wed; // 0, 1, 2 |
---|
455 | @Thu = 10;@ Fri = @iota - Wed + Thu - 1@; Sat; Sun ) // 10, 11, 12, 13 |
---|
456 | \end{Go} |
---|
457 | Note, \lstinline[language=Go]{iota} is advanced for an explicitly initialized enumerator, like the underscore @_@ identifier. |
---|
458 | |
---|
459 | Basic switch and looping are possible. |
---|
460 | \begin{cquote} |
---|
461 | \lstDeleteShortInline@ |
---|
462 | \setlength{\tabcolsep}{15pt} |
---|
463 | \begin{tabular}{@{}ll@{}} |
---|
464 | \begin{Go} |
---|
465 | day := Mon; |
---|
466 | switch day { |
---|
467 | case Mon, Tue, Wed, Thu, Fri: |
---|
468 | fmt.Println( "weekday" ); |
---|
469 | case Sat, Sun: |
---|
470 | fmt.Println( "weekend" ); |
---|
471 | } |
---|
472 | \end{Go} |
---|
473 | & |
---|
474 | \begin{Go} |
---|
475 | |
---|
476 | for i := Mon; i <= Sun; i += 1 { |
---|
477 | fmt.Println( i ) |
---|
478 | } |
---|
479 | |
---|
480 | |
---|
481 | |
---|
482 | \end{Go} |
---|
483 | \end{tabular} |
---|
484 | \lstMakeShortInline@ |
---|
485 | \end{cquote} |
---|
486 | However, the loop prints the values from 0 to 13 because there is no actual enumeration. |
---|
487 | |
---|
488 | |
---|
489 | \section{Java} |
---|
490 | \lstnewenvironment{Java}[1][]{\lstset{language=Java,morekeywords={enum,assert,strictfp}, |
---|
491 | escapechar=\$,moredelim=**[is][\color{red}]{!}{!},}\lstset{#1}}{} |
---|
492 | |
---|
493 | Every enumeration in Java is an enumeration class. |
---|
494 | For a basic enumeration |
---|
495 | \begin{Java} |
---|
496 | enum Weekday { Mon, Tue, Wed, Thu, Fri, Sat, Sun }; |
---|
497 | Weekday day = Weekday.Sat; |
---|
498 | \end{Java} |
---|
499 | the scoped enumerators are an ordered list of @final@ methods of type integer, ordered left to right starting at 0, increasing by 1. |
---|
500 | The value of an enumeration instance is restricted to the enumeration's enumerators. |
---|
501 | There is an implicit @int@ variable in the enumeration used to store the value of an enumeration instance. |
---|
502 | The position (ordinal) and label are accessible, where the value is the same as the position. |
---|
503 | \begin{Java} |
---|
504 | System.out.println( day.!ordinal()! + " " + day.!name()! ); // 5 Sat |
---|
505 | \end{Java} |
---|
506 | There is an inverse function @valueOf@ from string to enumerator. |
---|
507 | \begin{Java} |
---|
508 | day = Weekday.valueOf( "Wed" ); |
---|
509 | \end{Java} |
---|
510 | There are no implicit conversions to/from an enumerator and its underlying type. |
---|
511 | Like \Csharp, \VRef[Figure]{f:JavaFreeVersusClass} shows the same example for an enumeration with free routines for manipulation, and embedding the enumeration and operations into an enumeration class. |
---|
512 | |
---|
513 | \begin{figure} |
---|
514 | \centering |
---|
515 | \lstDeleteShortInline@ |
---|
516 | \begin{tabular}{@{}l|l@{}} |
---|
517 | \multicolumn{1}{@{}c|}{non-object oriented} & \multicolumn{1}{c@{}}{object oriented} \\ |
---|
518 | \hline |
---|
519 | \begin{Java} |
---|
520 | enum Weekday !{! |
---|
521 | Mon, Tue, Wed, Thu, Fri, Sat, Sun !}!; |
---|
522 | |
---|
523 | static boolean isWeekday( Weekday wd ) { |
---|
524 | return wd.ordinal() <= Weekday.Fri.ordinal(); |
---|
525 | } |
---|
526 | static boolean isWeekend( Weekday wd ) { |
---|
527 | return Weekday.Fri.ordinal() < wd.ordinal(); |
---|
528 | } |
---|
529 | |
---|
530 | public static void main( String[] args ) { |
---|
531 | Weekday day = Weekday.Sat; |
---|
532 | System.out.println( isWeekday( day ) ); |
---|
533 | System.out.println( isWeekend( day ) ); |
---|
534 | } |
---|
535 | \end{Java} |
---|
536 | & |
---|
537 | \begin{Java} |
---|
538 | enum Weekday !{! |
---|
539 | Mon, Tue, Wed, Thu, Fri, Sat, Sun; |
---|
540 | |
---|
541 | public boolean isWeekday() { |
---|
542 | return ordinal() <= Weekday.Fri.ordinal(); |
---|
543 | } |
---|
544 | public boolean isWeekend() { |
---|
545 | return Weekday.Fri.ordinal() < ordinal(); |
---|
546 | } |
---|
547 | !}! |
---|
548 | public static void main( String[] args ) { |
---|
549 | WeekDay day = WeekDay.Sat; |
---|
550 | System.out.println( day.isWeekday() ); |
---|
551 | System.out.println( day.isWeekend() ); |
---|
552 | } |
---|
553 | \end{Java} |
---|
554 | \end{tabular} |
---|
555 | \lstMakeShortInline@ |
---|
556 | \caption{Java: Free Routine Versus Class Enumeration} |
---|
557 | \label{f:JavaFreeVersusClass} |
---|
558 | \end{figure} |
---|
559 | |
---|
560 | To explicitly assign enumerator values and/or use a non-@int@ enumeration type (any Java type may be used), the enumeration must specify an explicit type in the enumeration class and a constructor. |
---|
561 | \begin{Java} |
---|
562 | enum Weekday { |
---|
563 | Mon!(1)!, Tue!(2)!, Wed!(3)!, Thu!(4)!, Fri!(5)!, Sat!(6)!, Sun!(7)!; // must appear first |
---|
564 | private !long! day; $\C{// underlying enumeration type}$ |
---|
565 | private Weekday( !long! d ) { day = d; } $\C{// used to initialize enumerators}$ |
---|
566 | }; |
---|
567 | Weekday day = Weekday.Sat; |
---|
568 | \end{Java} |
---|
569 | If an enumerator initialization is a runtime expression, the expression is executed once at the point the enumeration is declaraed. |
---|
570 | |
---|
571 | The position, value, and label are accessible. |
---|
572 | \begin{Java} |
---|
573 | System.out.println( !day.ordinal()! + " " + !day.day! + " " + !day.name()! ); // 5 6 Sat |
---|
574 | \end{Java} |
---|
575 | The constructor is private so only initialization or assignment can be used to set an enumeration, which ensures only corresponding enumerator values are allowed. |
---|
576 | |
---|
577 | An enumeration can appear in a @switch@ statement, but no ranges. |
---|
578 | \begin{Java} |
---|
579 | switch ( day ) { |
---|
580 | case Mon: case Tue: case Wed: case Thu: case Fri: |
---|
581 | System.out.println( "weekday" ); |
---|
582 | break; |
---|
583 | case Sat: case Sun: |
---|
584 | System.out.println( "weekend" ); |
---|
585 | break; |
---|
586 | } |
---|
587 | \end{Java} |
---|
588 | Like \Csharp, looping over an enumeration is done using method @values@, which returns the array of enumerator values (expensive operation). |
---|
589 | \begin{Java} |
---|
590 | for ( Weekday iday : Weekday.values() ) { |
---|
591 | System.out.print( iday.ordinal() + iday.day + " " + iday.name() + ", " ); |
---|
592 | } |
---|
593 | 0 1 Mon, 1 2 Tue, 2 3 Wed, 3 4 Thu, 4 5 Fri, 5 6 Sat, 6 7 Sun, |
---|
594 | \end{Java} |
---|
595 | |
---|
596 | As well, Java provides an @EnumSet@ where the underlying type is an efficient set of bits, one per enumeration \see{\Csharp \lstinline{Flags}, \VRef{s:Csharp}}, providing (logical) operations on groups of enumerators. |
---|
597 | There is also a specialized version of @HashMap@ with enumerator keys, which has performance benefits. |
---|
598 | |
---|
599 | Enumeration inheritence is disallowed because an enumeration is @final@. |
---|
600 | |
---|
601 | |
---|
602 | |
---|
603 | \section{Modula-3} |
---|
604 | |
---|
605 | |
---|
606 | |
---|
607 | \section{Rust} |
---|
608 | \lstnewenvironment{rust}[1][]{\lstset{language=Rust,escapechar=\$,moredelim=**[is][\color{red}]{@}{@},}\lstset{#1}}{} |
---|
609 | |
---|
610 | Rust provides a scoped enumeration based on variant types. |
---|
611 | % An enumeration, also referred to as an enum, is a simultaneous definition of a nominal enumerated type as well as a set of constructors, that can be used to create or pattern-match values of the corresponding enumerated type. |
---|
612 | An enumeration without constructors is called field-less. |
---|
613 | \begin{rust} |
---|
614 | enum Week { Mon, Tues, Wed, Thu, Fri, Sat, Sun@,@ } |
---|
615 | let mut week: Week = Week::Mon; |
---|
616 | week = Week::Fri; |
---|
617 | \end{rust} |
---|
618 | A field-less enumeration with only unit variants is called unit-only. |
---|
619 | \begin{rust} |
---|
620 | enum Week { Mon = 0, Tues = 1, Wed = 2, Thu = 3, Fri = 4, Sat = 5, Sun = 6 } |
---|
621 | \end{rust} |
---|
622 | Enum constructors can have either named or unnamed fields: |
---|
623 | \begin{rust} |
---|
624 | enum Animal { |
---|
625 | Dog( String, f64 ), |
---|
626 | Cat{ name: String, weight: f64 }, |
---|
627 | } |
---|
628 | let mut a: Animal = Animal::Dog("Cocoa".to_string(), 37.2); |
---|
629 | a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 }; |
---|
630 | \end{rust} |
---|
631 | Here, @Dog@ is an @enum@ variant, whereas @Cat@ is a struct-like variant. |
---|
632 | |
---|
633 | Each @enum@ type has an implicit integer tag (discriminant), with a unique value for each variant type. |
---|
634 | Like a C enumeration, the tag values for the variant types start at 0 with auto incrementing. |
---|
635 | The tag is re-purposed for enumeration by allowing it to be explicitly set, and auto incrmenting continues from that value. |
---|
636 | \begin{cquote} |
---|
637 | \sf\setlength{\tabcolsep}{3pt} |
---|
638 | \begin{tabular}{rcccccccr} |
---|
639 | @enum@ Week \{ & Mon, & Tue, & Wed = 2, & Thu = 10, & Fri, & Sat = 5, & Sun & \}; \\ |
---|
640 | \rm tags & 0 & 1 & 2 & 10 & 11 & 5 & 6 & \\ |
---|
641 | \end{tabular} |
---|
642 | \end{cquote} |
---|
643 | In general, the tag can only be read as an opaque reference for comparison. |
---|
644 | \begin{rust} |
---|
645 | if mem::discriminant(&week) == mem::discriminant(&Week::Mon) ... |
---|
646 | \end{rust} |
---|
647 | If the enumeration is unit-only, or field-less with no explicit discriminants and where only unit variants are explicit, then the discriminant is accessible with a numeric cast. |
---|
648 | \begin{rust} |
---|
649 | if week as isize == Week::Mon as isize ... |
---|
650 | \end{rust} |
---|
651 | |
---|
652 | |
---|
653 | \section{Swift} |
---|
654 | \lstnewenvironment{swift}[1][]{\lstset{language=Swift,escapechar=\$,moredelim=**[is][\color{red}]{@}{@},}\lstset{#1}}{} |
---|
655 | |
---|
656 | % https://www.programiz.com/swift/online-compiler |
---|
657 | |
---|
658 | A Swift enumeration provides a heterogenous set of enumerators, like a tagged @union@, where the field name is the enumerator and its list of type parameters form its type. |
---|
659 | \begin{swift} |
---|
660 | enum Many { |
---|
661 | case Mon, Tue, Wed, Thu, Fri, Sat, Sun // basic enumerator |
---|
662 | case code( String ) // string enumerator |
---|
663 | case tuple( Int, Int, Int ) // tuple enumerator |
---|
664 | }; |
---|
665 | var day = Many.Sat; // qualification to resolve type |
---|
666 | print( day ); |
---|
667 | day = .Wed // no qualification after type resolved |
---|
668 | print( day ); |
---|
669 | day = .code( "ABC" ); |
---|
670 | print( day ); |
---|
671 | day = .tuple( 1, 2, 3 ); |
---|
672 | print( day ); |
---|
673 | |
---|
674 | Sat |
---|
675 | Wed |
---|
676 | code("ABC") |
---|
677 | tuple(1, 2, 3) |
---|
678 | \end{swift} |
---|
679 | |
---|
680 | |
---|
681 | An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code. |
---|
682 | |
---|
683 | If you are familiar with C, you will know that C enumerations assign related names to a set of integer values. |
---|
684 | Enumerations in Swift are much more flexible, and don't have to provide a value for each case of the enumeration. |
---|
685 | If a value (known as a raw value) is provided for each enumeration case, the value can be a string, a character, or a value of any integer or floating-point type. |
---|
686 | |
---|
687 | Alternatively, enumeration cases can specify associated values of any type to be stored along with each different case value, much as unions or variants do in other languages. |
---|
688 | You can define a common set of related cases as part of one enumeration, each of which has a different set of values of appropriate types associated with it. |
---|
689 | |
---|
690 | Enumerations in Swift are first-class types in their own right. |
---|
691 | They adopt many features traditionally supported only by classes, such as computed properties to provide additional information about the enumeration's current value, and instance methods to provide functionality related to the values the enumeration represents. |
---|
692 | Enumerations can also define initializers to provide an initial case value; |
---|
693 | can be extended to expand their functionality beyond their original implementation; and can conform to protocols to provide standard functionality. |
---|
694 | |
---|
695 | For more about these capabilities, see Properties, Methods, Initialization, Extensions, and Protocols. |
---|
696 | |
---|
697 | \paragraph{Enumeration Syntax} |
---|
698 | |
---|
699 | |
---|
700 | Note: |
---|
701 | Swift enumeration cases don't have an integer value set by default, unlike languages like C and Objective-C. |
---|
702 | In the CompassPoint example above, @north@, @south@, @east@ and @west@ don't implicitly equal 0, 1, 2 and 3. |
---|
703 | Instead, the different enumeration cases are values in their own right, with an explicitly defined type of CompassPoint. |
---|
704 | |
---|
705 | Multiple cases can appear on a single line, separated by commas: |
---|
706 | \begin{swift} |
---|
707 | enum Planet { |
---|
708 | case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune |
---|
709 | } |
---|
710 | \end{swift} |
---|
711 | Each enumeration definition defines a new type. |
---|
712 | Like other types in Swift, their names (such as @CompassPoint@ and @Planet@) start with a capital letter. |
---|
713 | Give enumeration types singular rather than plural names, so that they read as self-evident: |
---|
714 | \begin{swift} |
---|
715 | var directionToHead = CompassPoint.west |
---|
716 | \end{swift} |
---|
717 | The type of @directionToHead@ is inferred when it's initialized with one of the possible values of @CompassPoint@. |
---|
718 | Once @directionToHead@ is declared as a @CompassPoint@, you can set it to a different @CompassPoint@ value using a shorter dot syntax: |
---|
719 | \begin{swift} |
---|
720 | directionToHead = .east |
---|
721 | \end{swift} |
---|
722 | The type of @directionToHead@ is already known, and so you can drop the type when setting its value. |
---|
723 | This makes for highly readable code when working with explicitly typed enumeration values. |
---|
724 | |
---|
725 | \paragraph{Matching Enumeration Values with a Switch Statement} |
---|
726 | |
---|
727 | You can match individual enumeration values with a switch statement: |
---|
728 | \begin{swift} |
---|
729 | directionToHead = .south |
---|
730 | switch directionToHead { |
---|
731 | case .north: |
---|
732 | print("Lots of planets have a north") |
---|
733 | case .south: |
---|
734 | print("Watch out for penguins") |
---|
735 | case .east: |
---|
736 | print("Where the sun rises") |
---|
737 | case .west: |
---|
738 | print("Where the skies are blue") |
---|
739 | } |
---|
740 | // Prints "Watch out for penguins" |
---|
741 | \end{swift} |
---|
742 | You can read this code as: |
---|
743 | \begin{quote} |
---|
744 | "Consider the value of directionToHead. |
---|
745 | In the case where it equals @.north@, print "Lots of planets have a north". |
---|
746 | In the case where it equals @.south@, print "Watch out for penguins"." |
---|
747 | |
---|
748 | ...and so on. |
---|
749 | \end{quote} |
---|
750 | As described in Control Flow, a switch statement must be exhaustive when considering an enumeration's cases. |
---|
751 | If the case for @.west@ is omitted, this code doesn't compile, because it doesn't consider the complete list of @CompassPoint@ cases. |
---|
752 | Requiring exhaustiveness ensures that enumeration cases aren't accidentally omitted. |
---|
753 | |
---|
754 | When it isn't appropriate to provide a case for every enumeration case, you can provide a default case to cover any cases that aren't addressed explicitly: |
---|
755 | \begin{swift} |
---|
756 | let somePlanet = Planet.earth |
---|
757 | switch somePlanet { |
---|
758 | case .earth: |
---|
759 | print("Mostly harmless") |
---|
760 | default: |
---|
761 | print("Not a safe place for humans") |
---|
762 | } |
---|
763 | // Prints "Mostly harmless" |
---|
764 | \end{swift} |
---|
765 | |
---|
766 | \paragraph{Iterating over Enumeration Cases} |
---|
767 | |
---|
768 | For some enumerations, it's useful to have a collection of all of that enumeration's cases. |
---|
769 | You enable this by writing @CaseIterable@ after the enumeration's name. |
---|
770 | Swift exposes a collection of all the cases as an allCases property of the enumeration type. |
---|
771 | Here's an example: |
---|
772 | \begin{swift} |
---|
773 | enum Beverage: CaseIterable { |
---|
774 | case coffee, tea, juice |
---|
775 | } |
---|
776 | let numberOfChoices = Beverage.allCases.count |
---|
777 | print("\(numberOfChoices) beverages available") |
---|
778 | // Prints "3 beverages available" |
---|
779 | \end{swift} |
---|
780 | In the example above, you write @Beverage.allCases@ to access a collection that contains all of the cases of the @Beverage@ enumeration. |
---|
781 | You can use @allCases@ like any other collection -- the collection's elements are instances of the enumeration type, so in this case they're Beverage values. |
---|
782 | The example above counts how many cases there are, and the example below uses a for-in loop to iterate over all the cases. |
---|
783 | \begin{swift} |
---|
784 | for beverage in Beverage.allCases { |
---|
785 | print(beverage) |
---|
786 | } |
---|
787 | // coffee |
---|
788 | // tea |
---|
789 | // juice |
---|
790 | \end{swift} |
---|
791 | The syntax used in the examples above marks the enumeration as conforming to the @CaseIterable@ protocol. |
---|
792 | For information about protocols, see Protocols. |
---|
793 | |
---|
794 | \paragraph{Associated Values} |
---|
795 | The examples in the previous section show how the cases of an enumeration are a defined (and typed) value in their own right. |
---|
796 | You can set a constant or variable to Planet.earth, and check for this value later. |
---|
797 | However, it's sometimes useful to be able to store values of other types alongside these case values. |
---|
798 | This additional information is called an associated value, and it varies each time you use that case as a value in your code. |
---|
799 | |
---|
800 | You can define Swift enumerations to store associated values of any given type, and the value types can be different for each case of the enumeration if needed. |
---|
801 | Enumerations similar to these are known as discriminated unions, tagged unions, or variants in other programming languages. |
---|
802 | |
---|
803 | For example, suppose an inventory tracking system needs to track products by two different types of barcode. |
---|
804 | Some products are labeled with 1D barcodes in UPC format, which uses the numbers 0 to 9. |
---|
805 | Each barcode has a number system digit, followed by five manufacturer code digits and five product code digits. |
---|
806 | These are followed by a check digit to verify that the code has been scanned correctly: |
---|
807 | |
---|
808 | Other products are labeled with 2D barcodes in QR code format, which can use any ISO 8859-1 character and can encode a string up to 2,953 characters long: |
---|
809 | |
---|
810 | It's convenient for an inventory tracking system to store UPC barcodes as a tuple of four integers, and QR code barcodes as a string of any length. |
---|
811 | |
---|
812 | In Swift, an enumeration to define product barcodes of either type might look like this: |
---|
813 | \begin{swift} |
---|
814 | enum Barcode { |
---|
815 | case upc(Int, Int, Int, Int) |
---|
816 | case qrCode(String) |
---|
817 | } |
---|
818 | \end{swift} |
---|
819 | This can be read as: |
---|
820 | \begin{quote} |
---|
821 | "Define an enumeration type called Barcode, which can take either a value of upc with an associated value of type @(Int, Int, Int, Int)@, or a value of @qrCode@ with an associated value of type @String@." |
---|
822 | \end{quote} |
---|
823 | This definition doesn't provide any actual @Int@ or @String@ values -- it just defines the type of associated values that Barcode constants and variables can store when they're equal to @Barcode.upc@ or @Barcode.qrCode@. |
---|
824 | |
---|
825 | You can then create new barcodes using either type: |
---|
826 | \begin{swift} |
---|
827 | var productBarcode = Barcode.upc(8, 85909, 51226, 3) |
---|
828 | \end{swift} |
---|
829 | This example creates a new variable called @productBarcode@ and assigns it a value of @Barcode.upc@ with an associated tuple value of @(8, 85909, 51226, 3)@. |
---|
830 | |
---|
831 | You can assign the same product a different type of barcode: |
---|
832 | \begin{swift} |
---|
833 | productBarcode = .qrCode("ABCDEFGHIJKLMNOP") |
---|
834 | \end{swift} |
---|
835 | At this point, the original @Barcode.upc@ and its integer values are replaced by the new @Barcode.qrCode@ and its string value. |
---|
836 | Constants and variables of type Barcode can store either a @.upc@ or a @.qrCode@ (together with their associated values), but they can store only one of them at any given time. |
---|
837 | |
---|
838 | You can check the different barcode types using a switch statement, similar to the example in Matching Enumeration Values with a Switch Statement. |
---|
839 | This time, however, the associated values are extracted as part of the switch statement. |
---|
840 | You extract each associated value as a constant (with the let prefix) or a variable (with the var prefix) for use within the switch case's body: |
---|
841 | \begin{swift} |
---|
842 | switch productBarcode { |
---|
843 | case .upc(let numberSystem, let manufacturer, let product, let check): |
---|
844 | print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).") |
---|
845 | case .qrCode(let productCode): |
---|
846 | print("QR code: \(productCode).") |
---|
847 | } |
---|
848 | // Prints "QR code: ABCDEFGHIJKLMNOP." |
---|
849 | \end{swift} |
---|
850 | If all of the associated values for an enumeration case are extracted as constants, or if all are extracted as variables, you can place a single let or var annotation before the case name, for brevity: |
---|
851 | \begin{swift} |
---|
852 | switch productBarcode { |
---|
853 | case let .upc(numberSystem, manufacturer, product, check): |
---|
854 | print("UPC : \(numberSystem), \(manufacturer), \(product), \(check).") |
---|
855 | case let .qrCode(productCode): |
---|
856 | print("QR code: \(productCode).") |
---|
857 | } |
---|
858 | // Prints "QR code: ABCDEFGHIJKLMNOP." |
---|
859 | \end{swift} |
---|
860 | |
---|
861 | \paragraph{Raw Values} |
---|
862 | |
---|
863 | The barcode example in Associated Values shows how cases of an enumeration can declare that they store associated values of different types. |
---|
864 | As an alternative to associated values, enumeration cases can come prepopulated with default values (called raw values), which are all of the same type. |
---|
865 | |
---|
866 | Here's an example that stores raw ASCII values alongside named enumeration cases: |
---|
867 | \begin{swift} |
---|
868 | enum ASCIIControlCharacter: Character { |
---|
869 | case tab = "\t" |
---|
870 | case lineFeed = "\n" |
---|
871 | case carriageReturn = "\r" |
---|
872 | } |
---|
873 | \end{swift} |
---|
874 | Here, the raw values for an enumeration called ASCIIControlCharacter are defined to be of type Character, and are set to some of the more common ASCII control characters. |
---|
875 | Character values are described in Strings and Characters. |
---|
876 | |
---|
877 | Raw values can be strings, characters, or any of the integer or floating-point number types. |
---|
878 | Each raw value must be unique within its enumeration declaration. |
---|
879 | |
---|
880 | Note |
---|
881 | |
---|
882 | Raw values are not the same as associated values. |
---|
883 | Raw values are set to prepopulated values when you first define the enumeration in your code, like the three ASCII codes above. |
---|
884 | The raw value for a particular enumeration case is always the same. |
---|
885 | Associated values are set when you create a new constant or variable based on one of the enumeration's cases, and can be different each time you do so. |
---|
886 | Implicitly Assigned Raw Values |
---|
887 | |
---|
888 | When you're working with enumerations that store integer or string raw values, you don't have to explicitly assign a raw value for each case. |
---|
889 | When you don't, Swift automatically assigns the values for you. |
---|
890 | |
---|
891 | For example, when integers are used for raw values, the implicit value for each case is one more than the previous case. |
---|
892 | If the first case doesn't have a value set, its value is 0. |
---|
893 | |
---|
894 | The enumeration below is a refinement of the earlier Planet enumeration, with integer raw values to represent each planet's order from the sun: |
---|
895 | |
---|
896 | \begin{swift} |
---|
897 | enum Planet: Int { |
---|
898 | case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune |
---|
899 | } |
---|
900 | \end{swift} |
---|
901 | In the example above, Planet.mercury has an explicit raw value of 1, Planet.venus has an implicit raw value of 2, and so on. |
---|
902 | |
---|
903 | When strings are used for raw values, the implicit value for each case is the text of that case's name. |
---|
904 | |
---|
905 | The enumeration below is a refinement of the earlier CompassPoint enumeration, with string raw values to represent each direction's name: |
---|
906 | \begin{swift} |
---|
907 | enum CompassPoint: String { |
---|
908 | case north, south, east, west |
---|
909 | } |
---|
910 | \end{swift} |
---|
911 | In the example above, CompassPoint.south has an implicit raw value of "south", and so on. |
---|
912 | |
---|
913 | You access the raw value of an enumeration case with its rawValue property: |
---|
914 | \begin{swift} |
---|
915 | let earthsOrder = Planet.earth.rawValue |
---|
916 | // earthsOrder is 3 |
---|
917 | |
---|
918 | let sunsetDirection = CompassPoint.west.rawValue |
---|
919 | // sunsetDirection is "west" |
---|
920 | \end{swift} |
---|
921 | |
---|
922 | \paragraph{Initializing from a Raw Value} |
---|
923 | |
---|
924 | If you define an enumeration with a raw-value type, the enumeration automatically receives an initializer that takes a value of the raw value's type (as a parameter called rawValue) and returns either an enumeration case or nil. |
---|
925 | You can use this initializer to try to create a new instance of the enumeration. |
---|
926 | |
---|
927 | This example identifies Uranus from its raw value of 7: |
---|
928 | \begin{swift} |
---|
929 | let possiblePlanet = Planet(rawValue: 7) |
---|
930 | // possiblePlanet is of type Planet? and equals Planet.uranus |
---|
931 | \end{swift} |
---|
932 | Not all possible Int values will find a matching planet, however. |
---|
933 | Because of this, the raw value initializer always returns an optional enumeration case. |
---|
934 | In the example above, possiblePlanet is of type Planet?, or "optional Planet." |
---|
935 | Note |
---|
936 | |
---|
937 | The raw value initializer is a failable initializer, because not every raw value will return an enumeration case. |
---|
938 | For more information, see Failable Initializers. |
---|
939 | |
---|
940 | If you try to find a planet with a position of 11, the optional Planet value returned by the raw value initializer will be nil: |
---|
941 | \begin{swift} |
---|
942 | let positionToFind = 11 |
---|
943 | if let somePlanet = Planet(rawValue: positionToFind) { |
---|
944 | switch somePlanet { |
---|
945 | case .earth: |
---|
946 | print("Mostly harmless") |
---|
947 | default: |
---|
948 | print("Not a safe place for humans") |
---|
949 | } |
---|
950 | } else { |
---|
951 | print("There isn't a planet at position \(positionToFind)") |
---|
952 | } |
---|
953 | // Prints "There isn't a planet at position 11" |
---|
954 | \end{swift} |
---|
955 | This example uses optional binding to try to access a planet with a raw value of 11. |
---|
956 | The statement if let somePlanet = Planet(rawValue: 11) creates an optional Planet, and sets somePlanet to the value of that optional Planet if it can be retrieved. |
---|
957 | In this case, it isn't possible to retrieve a planet with a position of 11, and so the else branch is executed instead. |
---|
958 | |
---|
959 | \paragraph{Recursive Enumerations} |
---|
960 | |
---|
961 | A recursive enumeration is an enumeration that has another instance of the enumeration as the associated value for one or more of the enumeration cases. |
---|
962 | You indicate that an enumeration case is recursive by writing indirect before it, which tells the compiler to insert the necessary layer of indirection. |
---|
963 | |
---|
964 | For example, here is an enumeration that stores simple arithmetic expressions: |
---|
965 | \begin{swift} |
---|
966 | enum ArithmeticExpression { |
---|
967 | case number(Int) |
---|
968 | indirect case addition(ArithmeticExpression, ArithmeticExpression) |
---|
969 | indirect case multiplication(ArithmeticExpression, ArithmeticExpression) |
---|
970 | } |
---|
971 | \end{swift} |
---|
972 | You can also write indirect before the beginning of the enumeration to enable indirection for all of the enumeration's cases that have an associated value: |
---|
973 | \begin{swift} |
---|
974 | indirect enum ArithmeticExpression { |
---|
975 | case number(Int) |
---|
976 | case addition(ArithmeticExpression, ArithmeticExpression) |
---|
977 | case multiplication(ArithmeticExpression, ArithmeticExpression) |
---|
978 | } |
---|
979 | \end{swift} |
---|
980 | This enumeration can store three kinds of arithmetic expressions: a plain number, the addition of two expressions, and the multiplication of two expressions. |
---|
981 | The addition and multiplication cases have associated values that are also arithmetic expressions -- these associated values make it possible to nest expressions. |
---|
982 | For example, the expression (5 + 4) * 2 has a number on the right-hand side of the multiplication and another expression on the left-hand side of the multiplication. |
---|
983 | Because the data is nested, the enumeration used to store the data also needs to support nesting -- this means the enumeration needs to be recursive. |
---|
984 | The code below shows the ArithmeticExpression recursive enumeration being created for (5 + 4) * 2: |
---|
985 | \begin{swift} |
---|
986 | let five = ArithmeticExpression.number(5) |
---|
987 | let four = ArithmeticExpression.number(4) |
---|
988 | let sum = ArithmeticExpression.addition(five, four) |
---|
989 | let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2)) |
---|
990 | \end{swift} |
---|
991 | A recursive function is a straightforward way to work with data that has a recursive structure. |
---|
992 | For example, here's a function that evaluates an arithmetic expression: |
---|
993 | \begin{swift} |
---|
994 | func evaluate(_ expression: ArithmeticExpression) -> Int { |
---|
995 | switch expression { |
---|
996 | case let .number(value): |
---|
997 | return value |
---|
998 | case let .addition(left, right): |
---|
999 | return evaluate(left) + evaluate(right) |
---|
1000 | case let .multiplication(left, right): |
---|
1001 | return evaluate(left) * evaluate(right) |
---|
1002 | } |
---|
1003 | } |
---|
1004 | |
---|
1005 | print(evaluate(product)) |
---|
1006 | // Prints "18" |
---|
1007 | \end{swift} |
---|
1008 | This function evaluates a plain number by simply returning the associated value. |
---|
1009 | It evaluates an addition or multiplication by evaluating the expression on the left-hand side, evaluating the expression on the right-hand side, and then adding them or multiplying them. |
---|
1010 | |
---|
1011 | |
---|
1012 | \section{Python} |
---|
1013 | \lstnewenvironment{python}[1][]{\lstset{language=Python,escapechar=\$,moredelim=**[is][\color{red}]{@}{@},}\lstset{#1}}{} |
---|
1014 | |
---|
1015 | A Python enumeration is a set of symbolic names bound to \emph{unique} values. |
---|
1016 | They are similar to global variables, but offer a more useful @repr()@, grouping, type-safety, and additional features. |
---|
1017 | Enumerations inherits from the @Enum@ class, \eg: |
---|
1018 | \begin{python} |
---|
1019 | class Weekday(@Enum@): Mon = 1; Tue = 2; Wed = 3; Thu = 4; Fri = 5; Sat = 6; Sun = 7 |
---|
1020 | class RGB(@Enum@): Red = 1; Green = 2; Blue = 3 |
---|
1021 | \end{python} |
---|
1022 | |
---|
1023 | Depending on the nature of the enum a member's value may or may not be important, but either way that value can be used to get the corresponding member: |
---|
1024 | \begin{python} |
---|
1025 | print( repr( Weekday( 3 ) ) ) |
---|
1026 | <Weekday.Wed: 3> |
---|
1027 | \end{python} |
---|
1028 | As you can see, the @repr()@ of a member shows the enum name, the member name, and the value. |
---|
1029 | The @str()@ of a member shows only the enum name and member name: |
---|
1030 | \begin{python} |
---|
1031 | print( str( Weekday.Thu ), Weekday.Thu ) |
---|
1032 | Weekday.Thu Weekday.Thu |
---|
1033 | \end{python} |
---|
1034 | The type of an enumeration member is the enum it belongs to: |
---|
1035 | \begin{python} |
---|
1036 | print( type( Weekday.Thu ) ) |
---|
1037 | <enum 'Weekday'> |
---|
1038 | print( isinstance(Weekday.Fri, Weekday) ) |
---|
1039 | True |
---|
1040 | \end{python} |
---|
1041 | Enum members have an attribute that contains just their name: |
---|
1042 | \begin{python} |
---|
1043 | print(Weekday.TUESDAY.name) |
---|
1044 | TUESDAY |
---|
1045 | \end{python} |
---|
1046 | Likewise, they have an attribute for their value: |
---|
1047 | \begin{python} |
---|
1048 | Weekday.WEDNESDAY.value |
---|
1049 | 3 |
---|
1050 | \end{python} |
---|
1051 | |
---|
1052 | Unlike many languages that treat enumerations solely as name/value pairs, Python @Enum@s can have behavior added. |
---|
1053 | For example, @datetime.date@ has two methods for returning the weekday: @weekday()@ and @isoweekday()@. |
---|
1054 | The difference is that one of them counts from 0-6 and the other from 1-7. |
---|
1055 | Rather than keep track of that ourselves we can add a method to the @Weekday@ enum to extract the day from the date instance and return the matching enum member: |
---|
1056 | \begin{python} |
---|
1057 | class Weekday(Enum): Mon = 1; Tue = 2; Wed = 3; Thu = 10; Fri = 15; Sat = 16; Sun = 17 |
---|
1058 | $@$classmethod |
---|
1059 | def from_date(cls, date): |
---|
1060 | return cls(date.isoweekday()) |
---|
1061 | \end{python} |
---|
1062 | Now we can find out what today is! Observe: |
---|
1063 | \begin{python} |
---|
1064 | >>> from datetime import date |
---|
1065 | >>> Weekday.from_date(date.today()) |
---|
1066 | <Weekday.TUESDAY: 2> |
---|
1067 | \end{python} |
---|
1068 | Of course, if you're reading this on some other day, you'll see that day instead. |
---|
1069 | |
---|
1070 | This Weekday enum is great if our variable only needs one day, but what if we need several? Maybe we're writing a function to plot chores during a week, and don't want to use a @list@ -- we could use a different type of @Enum@: |
---|
1071 | \begin{python} |
---|
1072 | from enum import Flag |
---|
1073 | class WeekdayF(@Flag@): Mon = @1@; Tue = @2@; Wed = @4@; Thu = @8@; Fri = @16@; Sat = @32@; Sun = @64@ |
---|
1074 | \end{python} |
---|
1075 | We've changed two things: we're inherited from @Flag@, and the values are all powers of 2. |
---|
1076 | |
---|
1077 | @Flag@ allows combining several members into a single variable: |
---|
1078 | \begin{python} |
---|
1079 | print( repr(WeekdayF.Sat | WeekdayF.Sun) ) |
---|
1080 | <WeekdayF.Sun|Sat: 96> |
---|
1081 | \end{python} |
---|
1082 | You can even iterate over a @Flag@ variable: |
---|
1083 | \begin{python} |
---|
1084 | for day in weekend: |
---|
1085 | print(day) |
---|
1086 | Weekday.SATURDAY |
---|
1087 | Weekday.SUNDAY |
---|
1088 | \end{python} |
---|
1089 | Okay, let's get some chores set up: |
---|
1090 | \begin{python} |
---|
1091 | >>> chores_for_ethan = { |
---|
1092 | ... 'feed the cat': Weekday.MONDAY | Weekday.WEDNESDAY | Weekday.FRIDAY, |
---|
1093 | ... 'do the dishes': Weekday.TUESDAY | Weekday.THURSDAY, |
---|
1094 | ... 'answer SO questions': Weekday.SATURDAY, |
---|
1095 | ... } |
---|
1096 | \end{python} |
---|
1097 | And a function to display the chores for a given day: |
---|
1098 | \begin{python} |
---|
1099 | >>> def show_chores(chores, day): |
---|
1100 | ... for chore, days in chores.items(): |
---|
1101 | ... if day in days: |
---|
1102 | ... print(chore) |
---|
1103 | >>> show_chores(chores_for_ethan, Weekday.SATURDAY) |
---|
1104 | answer SO questions |
---|
1105 | \end{python} |
---|
1106 | In cases where the actual values of the members do not matter, you can save yourself some work and use @auto()@ for the values: |
---|
1107 | \begin{python} |
---|
1108 | >>> from enum import auto |
---|
1109 | >>> class Weekday(Flag): |
---|
1110 | ... MONDAY = auto() |
---|
1111 | ... TUESDAY = auto() |
---|
1112 | ... WEDNESDAY = auto() |
---|
1113 | ... THURSDAY = auto() |
---|
1114 | ... FRIDAY = auto() |
---|
1115 | ... SATURDAY = auto() |
---|
1116 | ... SUNDAY = auto() |
---|
1117 | ... WEEKEND = SATURDAY | SUNDAY |
---|
1118 | \end{python} |
---|
1119 | |
---|
1120 | \subsection{Programmatic access to enumeration members and their attributes} |
---|
1121 | |
---|
1122 | Sometimes it's useful to access members in enumerations programmatically (i.e. situations where @Color.RED@ won't do because the exact color is not known at program-writing time). |
---|
1123 | @Enum@ allows such access: |
---|
1124 | \begin{python} |
---|
1125 | >>> Color(1) |
---|
1126 | <Color.RED: 1> |
---|
1127 | >>> Color(3) |
---|
1128 | <Color.BLUE: 3> |
---|
1129 | \end{python} |
---|
1130 | If you want to access enum members by name, use item access: |
---|
1131 | \begin{python} |
---|
1132 | Color['RED'] |
---|
1133 | <Color.RED: 1> |
---|
1134 | |
---|
1135 | Color['GREEN'] |
---|
1136 | <Color.GREEN: 2> |
---|
1137 | \end{python} |
---|
1138 | If you have an enum member and need its name or value: |
---|
1139 | \begin{python} |
---|
1140 | >>> member = Color.RED |
---|
1141 | >>> member.name |
---|
1142 | 'RED' |
---|
1143 | >>> member.value |
---|
1144 | 1 |
---|
1145 | \end{python} |
---|
1146 | |
---|
1147 | \subsection{Duplicating enum members and values} |
---|
1148 | |
---|
1149 | An enum member can have other names associated with it. |
---|
1150 | Given two entries @A@ and @B@ with the same value (and @A@ defined first), @B@ is an alias for the member @A@. |
---|
1151 | By-value lookup of the value of @A@ will return the member @A@. |
---|
1152 | By-name lookup of @A@ will return the member @A@. |
---|
1153 | By-name lookup of @B@ will also return the member @A@: |
---|
1154 | \begin{python} |
---|
1155 | class Shape(Enum): SQUARE = 2; DIAMOND = 1; CIRCLE = 3; ALIAS_FOR_SQUARE = 2 |
---|
1156 | >>> Shape.SQUARE |
---|
1157 | <Shape.SQUARE: 2> |
---|
1158 | >>> Shape.ALIAS_FOR_SQUARE |
---|
1159 | <Shape.SQUARE: 2> |
---|
1160 | >>> Shape(2) |
---|
1161 | <Shape.SQUARE: 2> |
---|
1162 | \end{python} |
---|
1163 | |
---|
1164 | Note: Attempting to create a member with the same name as an already defined attribute (another member, a method, etc.) or attempting to create an attribute with the same name as a member is not allowed. |
---|
1165 | |
---|
1166 | \subsection{Ensuring unique enumeration values} |
---|
1167 | |
---|
1168 | By default, enumerations allow multiple names as aliases for the same value. |
---|
1169 | When this behavior isn't desired, you can use the @unique()@ decorator: |
---|
1170 | \begin{python} |
---|
1171 | from enum import Enum, unique |
---|
1172 | $@$unique |
---|
1173 | class DupVal(Enum): ONE = 1; TWO = 2; THREE = 3; FOUR = 3 |
---|
1174 | ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE |
---|
1175 | \end{python} |
---|
1176 | |
---|
1177 | \subsection{Using automatic values} |
---|
1178 | |
---|
1179 | If the exact value is unimportant you can use @auto@: |
---|
1180 | \begin{python} |
---|
1181 | from enum import Enum, auto |
---|
1182 | class RGBa(Enum): RED = auto(); BLUE = auto(); GREEN = auto() |
---|
1183 | \end{python} |
---|
1184 | (Like Golang @iota@.) |
---|
1185 | The values are chosen by @_generate_next_value_()@, which can be overridden: |
---|
1186 | \begin{python} |
---|
1187 | >>> class AutoName(Enum): |
---|
1188 | ... $@$staticmethod |
---|
1189 | ... def _generate_next_value_(name, start, count, last_values): |
---|
1190 | ... return name |
---|
1191 | ... |
---|
1192 | >>> class Ordinal(AutoName): |
---|
1193 | ... NORTH = auto() |
---|
1194 | ... SOUTH = auto() |
---|
1195 | ... EAST = auto() |
---|
1196 | ... WEST = auto() |
---|
1197 | ... |
---|
1198 | >>> [member.value for member in Ordinal] |
---|
1199 | ['NORTH', 'SOUTH', 'EAST', 'WEST'] |
---|
1200 | \end{python} |
---|
1201 | Note The @_generate_next_value_()@ method must be defined before any members. |
---|
1202 | |
---|
1203 | \subsection{Iteration} |
---|
1204 | |
---|
1205 | Iterating over the members of an enum does not provide the aliases: |
---|
1206 | \begin{python} |
---|
1207 | >>> list(Shape) |
---|
1208 | [<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>] |
---|
1209 | >>> list(Weekday) |
---|
1210 | [<Weekday.MONDAY: 1>, <Weekday.TUESDAY: 2>, <Weekday.WEDNESDAY: 4>, <Weekday.THURSDAY: 8>, |
---|
1211 | <Weekday.FRIDAY: 16>, <Weekday.SATURDAY: 32>, <Weekday.SUNDAY: 64>] |
---|
1212 | \end{python} |
---|
1213 | Note that the aliases @Shape.ALIAS_FOR_SQUARE@ and @Weekday.WEEKEND@ aren't shown. |
---|
1214 | |
---|
1215 | The special attribute @__members__@ is a read-only ordered mapping of names to members. |
---|
1216 | It includes all names defined in the enumeration, including the aliases: |
---|
1217 | \begin{python} |
---|
1218 | >>> for name, member in Shape.__members__.items(): |
---|
1219 | ... name, member |
---|
1220 | ... |
---|
1221 | ('SQUARE', <Shape.SQUARE: 2>) |
---|
1222 | ('DIAMOND', <Shape.DIAMOND: 1>) |
---|
1223 | ('CIRCLE', <Shape.CIRCLE: 3>) |
---|
1224 | ('ALIAS_FOR_SQUARE', <Shape.SQUARE: 2>) |
---|
1225 | \end{python} |
---|
1226 | The @__members__@ attribute can be used for detailed programmatic access to the enumeration members. |
---|
1227 | For example, finding all the aliases: |
---|
1228 | \begin{python} |
---|
1229 | >>> [name for name, member in Shape.__members__.items() if member.name != name] |
---|
1230 | ['ALIAS_FOR_SQUARE'] |
---|
1231 | \end{python} |
---|
1232 | Note: Aliases for flags include values with multiple flags set, such as 3, and no flags set, i.e. 0. |
---|
1233 | |
---|
1234 | \subsection{Comparisons} |
---|
1235 | |
---|
1236 | Enumeration members are compared by identity: |
---|
1237 | \begin{python} |
---|
1238 | >>> Color.RED is Color.RED |
---|
1239 | True |
---|
1240 | >>> Color.RED is Color.BLUE |
---|
1241 | False |
---|
1242 | >>> Color.RED is not Color.BLUE |
---|
1243 | True |
---|
1244 | \end{python} |
---|
1245 | Ordered comparisons between enumeration values are not supported. |
---|
1246 | Enum members are not integers (but see @IntEnum@ below): |
---|
1247 | \begin{python} |
---|
1248 | >>> Color.RED < Color.BLUE |
---|
1249 | Traceback (most recent call last): |
---|
1250 | File "<stdin>", line 1, in <module> |
---|
1251 | TypeError: '<' not supported between instances of 'Color' and 'Color' |
---|
1252 | \end{python} |
---|
1253 | Equality comparisons are defined though: |
---|
1254 | \begin{python} |
---|
1255 | >>> Color.BLUE == Color.RED |
---|
1256 | False |
---|
1257 | >>> Color.BLUE != Color.RED |
---|
1258 | True |
---|
1259 | >>> Color.BLUE == Color.BLUE |
---|
1260 | True |
---|
1261 | \end{python} |
---|
1262 | Comparisons against non-enumeration values will always compare not equal (again, @IntEnum@ was explicitly designed to behave differently, see below): |
---|
1263 | \begin{python} |
---|
1264 | >>> Color.BLUE == 2 |
---|
1265 | False |
---|
1266 | \end{python} |
---|
1267 | |
---|
1268 | Warning: It is possible to reload modules -- if a reloaded module contains enums, they will be recreated, and the new members may not compare identical/equal to the original members. |
---|
1269 | |
---|
1270 | \subsection{Allowed members and attributes of enumerations} |
---|
1271 | |
---|
1272 | Most of the examples above use integers for enumeration values. |
---|
1273 | Using integers is short and handy (and provided by default by the Functional API), but not strictly enforced. |
---|
1274 | In the vast majority of use-cases, one doesn't care what the actual value of an enumeration is. |
---|
1275 | But if the value is important, enumerations can have arbitrary values. |
---|
1276 | |
---|
1277 | Enumerations are Python classes, and can have methods and special methods as usual. If we have this enumeration: |
---|
1278 | \begin{python} |
---|
1279 | >>> class Mood(Enum): |
---|
1280 | ... FUNKY = 1 |
---|
1281 | ... HAPPY = 3 |
---|
1282 | ... |
---|
1283 | ... def describe(self): |
---|
1284 | ... # self is the member here |
---|
1285 | ... return self.name, self.value |
---|
1286 | ... |
---|
1287 | ... def __str__(self): |
---|
1288 | ... return 'my custom str! {0}'.format(self.value) |
---|
1289 | ... |
---|
1290 | ... $@$classmethod |
---|
1291 | ... |
---|
1292 | ... def favorite_mood(cls): |
---|
1293 | ... # cls here is the enumeration |
---|
1294 | ... return cls.HAPPY |
---|
1295 | ... |
---|
1296 | \end{python} |
---|
1297 | Then: |
---|
1298 | \begin{python} |
---|
1299 | >>> Mood.favorite_mood() |
---|
1300 | <Mood.HAPPY: 3> |
---|
1301 | >>> Mood.HAPPY.describe() |
---|
1302 | ('HAPPY', 3) |
---|
1303 | >>> str(Mood.FUNKY) |
---|
1304 | 'my custom str! 1' |
---|
1305 | \end{python} |
---|
1306 | The rules for what is allowed are as follows: names that start and end with a single underscore are reserved by enum and cannot be used; |
---|
1307 | all other attributes defined within an enumeration will become members of this enumeration, with the exception of special methods (@__str__()@, @__add__()@, etc.), descriptors (methods are also descriptors), and variable names listed in @_ignore_@. |
---|
1308 | |
---|
1309 | Note: if your enumeration defines @__new__()@ and/or @__init__()@, any value(s) given to the enum member will be passed into those methods. |
---|
1310 | See Planet for an example. |
---|
1311 | |
---|
1312 | Note: The @__new__()@ method, if defined, is used during creation of the Enum members; |
---|
1313 | it is then replaced by Enum's @__new__()@ which is used after class creation for lookup of existing members. |
---|
1314 | See When to use @__new__()@ vs. @__init__()@ for more details. |
---|
1315 | |
---|
1316 | \subsection{Restricted Enum subclassing} |
---|
1317 | |
---|
1318 | A new @Enum@ class must have one base enum class, up to one concrete data type, and as many object-based mixin classes as needed. |
---|
1319 | The order of these base classes is: |
---|
1320 | \begin{python} |
---|
1321 | class EnumName([mix-in, ...,] [data-type,] base-enum): |
---|
1322 | pass |
---|
1323 | \end{python} |
---|
1324 | Also, subclassing an enumeration is allowed only if the enumeration does not define any members. |
---|
1325 | So this is forbidden: |
---|
1326 | \begin{python} |
---|
1327 | >>> class MoreColor(Color): |
---|
1328 | ... PINK = 17 |
---|
1329 | ... |
---|
1330 | Traceback (most recent call last): |
---|
1331 | ... |
---|
1332 | TypeError: <enum 'MoreColor'> cannot extend <enum 'Color'> |
---|
1333 | \end{python} |
---|
1334 | But this is allowed: |
---|
1335 | \begin{python} |
---|
1336 | >>> class Foo(Enum): |
---|
1337 | ... def some_behavior(self): |
---|
1338 | ... pass |
---|
1339 | ... |
---|
1340 | >>> class Bar(Foo): |
---|
1341 | ... HAPPY = 1 |
---|
1342 | ... SAD = 2 |
---|
1343 | ... |
---|
1344 | \end{python} |
---|
1345 | Allowing subclassing of enums that define members would lead to a violation of some important invariants of types and instances. |
---|
1346 | On the other hand, it makes sense to allow sharing some common behavior between a group of enumerations. (See OrderedEnum for an example.) |
---|
1347 | |
---|
1348 | \subsection{Dataclass support} |
---|
1349 | |
---|
1350 | When inheriting from a @dataclass@, the @__repr__()@ omits the inherited class' name. |
---|
1351 | For example: |
---|
1352 | \begin{python} |
---|
1353 | >>> from dataclasses import dataclass, field |
---|
1354 | >>> $@$dataclass |
---|
1355 | ... class CreatureDataMixin: |
---|
1356 | ... size: str |
---|
1357 | ... legs: int |
---|
1358 | ... tail: bool = field(repr=False, default=True) |
---|
1359 | ... |
---|
1360 | >>> class Creature(CreatureDataMixin, Enum): |
---|
1361 | ... BEETLE = 'small', 6 |
---|
1362 | ... DOG = 'medium', 4 |
---|
1363 | ... |
---|
1364 | >>> Creature.DOG |
---|
1365 | <Creature.DOG: size='medium', legs=4> |
---|
1366 | \end{python} |
---|
1367 | Use the @dataclass()@ argument repr=False to use the standard @repr()@. |
---|
1368 | |
---|
1369 | Changed in version 3.12: Only the dataclass fields are shown in the value area, not the dataclass' name. |
---|
1370 | |
---|
1371 | \subsection{Pickling} |
---|
1372 | |
---|
1373 | Enumerations can be pickled and unpickled: |
---|
1374 | \begin{python} |
---|
1375 | >>> from test.test_enum import Fruit |
---|
1376 | >>> from pickle import dumps, loads |
---|
1377 | >>> Fruit.TOMATO is loads(dumps(Fruit.TOMATO)) |
---|
1378 | True |
---|
1379 | \end{python} |
---|
1380 | The usual restrictions for pickling apply: picklable enums must be defined in the top level of a module, since unpickling requires them to be importable from that module. |
---|
1381 | |
---|
1382 | Note: With pickle protocol version 4 it is possible to easily pickle enums nested in other classes. |
---|
1383 | |
---|
1384 | It is possible to modify how enum members are pickled/unpickled by defining @__reduce_ex__()@ in the enumeration class. |
---|
1385 | The default method is by-value, but enums with complicated values may want to use by-name: |
---|
1386 | \begin{python} |
---|
1387 | >>> import enum |
---|
1388 | >>> class MyEnum(enum.Enum): |
---|
1389 | ... __reduce_ex__ = enum.pickle_by_enum_name |
---|
1390 | \end{python} |
---|
1391 | Note: Using by-name for flags is not recommended, as unnamed aliases will not unpickle. |
---|
1392 | |
---|
1393 | \subsection{Functional API} |
---|
1394 | |
---|
1395 | The @Enum@ class is callable, providing the following functional API: |
---|
1396 | \begin{python} |
---|
1397 | >>> Animal = Enum('Animal', 'ANT BEE CAT DOG') |
---|
1398 | >>> Animal |
---|
1399 | <enum 'Animal'> |
---|
1400 | >>> Animal.ANT |
---|
1401 | <Animal.ANT: 1> |
---|
1402 | >>> list(Animal) |
---|
1403 | [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>, <Animal.DOG: 4>] |
---|
1404 | \end{python} |
---|
1405 | The semantics of this API resemble @namedtuple@. |
---|
1406 | The first argument of the call to @Enum@ is the name of the enumeration. |
---|
1407 | |
---|
1408 | The second argument is the source of enumeration member names. |
---|
1409 | It can be a whitespace-separated string of names, a sequence of names, a sequence of 2-tuples with key/value pairs, or a mapping (e.g. dictionary) of names to values. |
---|
1410 | The last two options enable assigning arbitrary values to enumerations; |
---|
1411 | the others auto-assign increasing integers starting with 1 (use the @start@ parameter to specify a different starting value). |
---|
1412 | A new class derived from @Enum@ is returned. |
---|
1413 | In other words, the above assignment to Animal is equivalent to: |
---|
1414 | \begin{python} |
---|
1415 | >>> class Animal(Enum): |
---|
1416 | ... ANT = 1 |
---|
1417 | ... BEE = 2 |
---|
1418 | ... CAT = 3 |
---|
1419 | ... DOG = 4 |
---|
1420 | ... |
---|
1421 | \end{python} |
---|
1422 | The reason for defaulting to 1 as the starting number and not 0 is that 0 is @False@ in a boolean sense, but by default enum members all evaluate to @True@. |
---|
1423 | |
---|
1424 | Pickling enums created with the functional API can be tricky as frame stack implementation details are used to try and figure out which module the enumeration is being created in (e.g. it will fail if you use a utility function in a separate module, and also may not work on IronPython or Jython). |
---|
1425 | The solution is to specify the module name explicitly as follows: |
---|
1426 | \begin{python} |
---|
1427 | >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', module=__name__) |
---|
1428 | \end{python} |
---|
1429 | Warning: If module is not supplied, and @Enum@ cannot determine what it is, the new @Enum@ members will not be unpicklable; to keep errors closer to the source, pickling will be disabled. |
---|
1430 | |
---|
1431 | The new pickle protocol 4 also, in some circumstances, relies on @__qualname__@ being set to the location where pickle will be able to find the class. |
---|
1432 | For example, if the class was made available in class SomeData in the global scope: |
---|
1433 | \begin{python} |
---|
1434 | >>> Animal = Enum('Animal', 'ANT BEE CAT DOG', qualname='SomeData.Animal') |
---|
1435 | \end{python} |
---|
1436 | The complete signature is: |
---|
1437 | \begin{python} |
---|
1438 | Enum( |
---|
1439 | value='NewEnumName', |
---|
1440 | names=<...>, |
---|
1441 | *, |
---|
1442 | module='...', |
---|
1443 | qualname='...', |
---|
1444 | type=<mixed-in class>, |
---|
1445 | start=1, |
---|
1446 | ) |
---|
1447 | \end{python} |
---|
1448 | \begin{itemize} |
---|
1449 | \item |
---|
1450 | @value@: What the new enum class will record as its name. |
---|
1451 | \item |
---|
1452 | @names@: The enum members. |
---|
1453 | This can be a whitespace- or comma-separated string (values will start at 1 unless otherwise specified): |
---|
1454 | \begin{python} |
---|
1455 | 'RED GREEN BLUE' | 'RED,GREEN,BLUE' | 'RED, GREEN, BLUE' |
---|
1456 | \end{python} |
---|
1457 | or an iterator of names: |
---|
1458 | \begin{python} |
---|
1459 | ['RED', 'GREEN', 'BLUE'] |
---|
1460 | \end{python} |
---|
1461 | or an iterator of (name, value) pairs: |
---|
1462 | \begin{python} |
---|
1463 | [('CYAN', 4), ('MAGENTA', 5), ('YELLOW', 6)] |
---|
1464 | \end{python} |
---|
1465 | or a mapping: |
---|
1466 | \begin{python} |
---|
1467 | {'CHARTREUSE': 7, 'SEA_GREEN': 11, 'ROSEMARY': 42} |
---|
1468 | \end{python} |
---|
1469 | \item |
---|
1470 | module: name of module where new enum class can be found. |
---|
1471 | \item |
---|
1472 | @qualname@: where in module new enum class can be found. |
---|
1473 | \item |
---|
1474 | @type@: type to mix in to new enum class. |
---|
1475 | \item |
---|
1476 | @start@: number to start counting at if only names are passed in. |
---|
1477 | \end{itemize} |
---|
1478 | Changed in version 3.5: The start parameter was added. |
---|
1479 | |
---|
1480 | \subsection{Derived Enumerations} |
---|
1481 | |
---|
1482 | \subsection{IntEnum} |
---|
1483 | |
---|
1484 | The first variation of @Enum@ that is provided is also a subclass of @int@. |
---|
1485 | Members of an @IntEnum@ can be compared to integers; |
---|
1486 | by extension, integer enumerations of different types can also be compared to each other: |
---|
1487 | \begin{python} |
---|
1488 | >>> from enum import IntEnum |
---|
1489 | >>> class Shape(IntEnum): |
---|
1490 | ... CIRCLE = 1 |
---|
1491 | ... SQUARE = 2 |
---|
1492 | ... |
---|
1493 | >>> class Request(IntEnum): |
---|
1494 | ... POST = 1 |
---|
1495 | ... GET = 2 |
---|
1496 | ... |
---|
1497 | >>> Shape == 1 |
---|
1498 | False |
---|
1499 | >>> Shape.CIRCLE == 1 |
---|
1500 | True |
---|
1501 | >>> Shape.CIRCLE == Request.POST |
---|
1502 | True |
---|
1503 | \end{python} |
---|
1504 | However, they still can't be compared to standard @Enum@ enumerations: |
---|
1505 | \begin{python} |
---|
1506 | >>> class Shape(IntEnum): |
---|
1507 | ... CIRCLE = 1 |
---|
1508 | ... SQUARE = 2 |
---|
1509 | ... |
---|
1510 | >>> class Color(Enum): |
---|
1511 | ... RED = 1 |
---|
1512 | ... GREEN = 2 |
---|
1513 | ... |
---|
1514 | >>> Shape.CIRCLE == Color.RED |
---|
1515 | False |
---|
1516 | \end{python} |
---|
1517 | @IntEnum@ values behave like integers in other ways you'd expect: |
---|
1518 | \begin{python} |
---|
1519 | >>> int(Shape.CIRCLE) |
---|
1520 | 1 |
---|
1521 | >>> ['a', 'b', 'c'][Shape.CIRCLE] |
---|
1522 | 'b' |
---|
1523 | >>> [i for i in range(Shape.SQUARE)] |
---|
1524 | [0, 1] |
---|
1525 | \end{python} |
---|
1526 | |
---|
1527 | \subsection{StrEnum} |
---|
1528 | |
---|
1529 | The second variation of @Enum@ that is provided is also a subclass of @str@. |
---|
1530 | Members of a @StrEnum@ can be compared to strings; |
---|
1531 | by extension, string enumerations of different types can also be compared to each other. |
---|
1532 | |
---|
1533 | New in version 3.11. |
---|
1534 | |
---|
1535 | \subsection{IntFlag} |
---|
1536 | |
---|
1537 | The next variation of @Enum@ provided, @IntFlag@, is also based on @int@. |
---|
1538 | The difference being @IntFlag@ members can be combined using the bitwise operators (@&, |, ^, ~@) and the result is still an @IntFlag@ member, if possible. |
---|
1539 | Like @IntEnum@, @IntFlag@ members are also integers and can be used wherever an int is used. |
---|
1540 | |
---|
1541 | Note: Any operation on an IntFlag member besides the bit-wise operations will lose the @IntFlag@ membership. |
---|
1542 | |
---|
1543 | Bit-wise operations that result in invalid @IntFlag@ values will lose the @IntFlag@ membership. |
---|
1544 | See @FlagBoundary@ for details. |
---|
1545 | |
---|
1546 | New in version 3.6. |
---|
1547 | |
---|
1548 | Changed in version 3.11. |
---|
1549 | |
---|
1550 | Sample @IntFlag@ class: |
---|
1551 | \begin{python} |
---|
1552 | >>> from enum import IntFlag |
---|
1553 | >>> class Perm(IntFlag): |
---|
1554 | ... R = 4 |
---|
1555 | ... W = 2 |
---|
1556 | ... X = 1 |
---|
1557 | ... |
---|
1558 | >>> Perm.R | Perm.W |
---|
1559 | <Perm.R|W: 6> |
---|
1560 | >>> Perm.R + Perm.W |
---|
1561 | 6 |
---|
1562 | >>> RW = Perm.R | Perm.W |
---|
1563 | >>> Perm.R in RW |
---|
1564 | True |
---|
1565 | \end{python} |
---|
1566 | It is also possible to name the combinations: |
---|
1567 | \begin{python} |
---|
1568 | >>> class Perm(IntFlag): |
---|
1569 | ... R = 4 |
---|
1570 | ... W = 2 |
---|
1571 | ... X = 1 |
---|
1572 | ... RWX = 7 |
---|
1573 | ... |
---|
1574 | >>> Perm.RWX |
---|
1575 | <Perm.RWX: 7> |
---|
1576 | >>> ~Perm.RWX |
---|
1577 | <Perm: 0> |
---|
1578 | >>> Perm(7) |
---|
1579 | <Perm.RWX: 7> |
---|
1580 | \end{python} |
---|
1581 | Note: Named combinations are considered aliases. Aliases do not show up during iteration, but can be returned from by-value lookups. |
---|
1582 | |
---|
1583 | Changed in version 3.11. |
---|
1584 | |
---|
1585 | Another important difference between @IntFlag@ and @Enum@ is that if no flags are set (the value is 0), its boolean evaluation is @False@: |
---|
1586 | \begin{python} |
---|
1587 | >>> Perm.R & Perm.X |
---|
1588 | <Perm: 0> |
---|
1589 | >>> bool(Perm.R & Perm.X) |
---|
1590 | False |
---|
1591 | \end{python} |
---|
1592 | Because @IntFlag@ members are also subclasses of int they can be combined with them (but may lose @IntFlag@ membership: |
---|
1593 | \begin{python} |
---|
1594 | >>> Perm.X | 4 |
---|
1595 | <Perm.R|X: 5> |
---|
1596 | |
---|
1597 | >>> Perm.X + 8 |
---|
1598 | 9 |
---|
1599 | \end{python} |
---|
1600 | Note: The negation operator, @~@, always returns an @IntFlag@ member with a positive value: |
---|
1601 | \begin{python} |
---|
1602 | >>> (~Perm.X).value == (Perm.R|Perm.W).value == 6 |
---|
1603 | True |
---|
1604 | \end{python} |
---|
1605 | @IntFlag@ members can also be iterated over: |
---|
1606 | \begin{python} |
---|
1607 | >>> list(RW) |
---|
1608 | [<Perm.R: 4>, <Perm.W: 2>] |
---|
1609 | \end{python} |
---|
1610 | New in version 3.11. |
---|
1611 | |
---|
1612 | \subsection{Flag} |
---|
1613 | |
---|
1614 | The last variation is @Flag@. |
---|
1615 | Like @IntFlag@, @Flag@ members can be combined using the bitwise operators (@&, |, ^, ~@). |
---|
1616 | Unlike @IntFlag@, they cannot be combined with, nor compared against, any other @Flag@ enumeration, nor @int@. |
---|
1617 | While it is possible to specify the values directly it is recommended to use @auto@ as the value and let @Flag@ select an appropriate value. |
---|
1618 | |
---|
1619 | New in version 3.6. |
---|
1620 | |
---|
1621 | Like @IntFlag@, if a combination of @Flag@ members results in no flags being set, the boolean evaluation is @False@: |
---|
1622 | \begin{python} |
---|
1623 | >>> from enum import Flag, auto |
---|
1624 | >>> class Color(Flag): |
---|
1625 | ... RED = auto() |
---|
1626 | ... BLUE = auto() |
---|
1627 | ... GREEN = auto() |
---|
1628 | ... |
---|
1629 | >>> Color.RED & Color.GREEN |
---|
1630 | <Color: 0> |
---|
1631 | >>> bool(Color.RED & Color.GREEN) |
---|
1632 | False |
---|
1633 | \end{python} |
---|
1634 | Individual flags should have values that are powers of two (1, 2, 4, 8, ...), while combinations of flags will not: |
---|
1635 | \begin{python} |
---|
1636 | >>> class Color(Flag): |
---|
1637 | ... RED = auto() |
---|
1638 | ... BLUE = auto() |
---|
1639 | ... GREEN = auto() |
---|
1640 | ... WHITE = RED | BLUE | GREEN |
---|
1641 | ... |
---|
1642 | >>> Color.WHITE |
---|
1643 | <Color.WHITE: 7> |
---|
1644 | \end{python} |
---|
1645 | Giving a name to the ``no flags set'' condition does not change its boolean value: |
---|
1646 | \begin{python} |
---|
1647 | >>> class Color(Flag): |
---|
1648 | ... BLACK = 0 |
---|
1649 | ... RED = auto() |
---|
1650 | ... BLUE = auto() |
---|
1651 | ... GREEN = auto() |
---|
1652 | ... |
---|
1653 | >>> Color.BLACK |
---|
1654 | <Color.BLACK: 0> |
---|
1655 | >>> bool(Color.BLACK) |
---|
1656 | False |
---|
1657 | \end{python} |
---|
1658 | @Flag@ members can also be iterated over: |
---|
1659 | \begin{python} |
---|
1660 | >>> purple = Color.RED | Color.BLUE |
---|
1661 | >>> list(purple) |
---|
1662 | [<Color.RED: 1>, <Color.BLUE: 2>] |
---|
1663 | \end{python} |
---|
1664 | New in version 3.11. |
---|
1665 | |
---|
1666 | Note: For the majority of new code, @Enum@ and @Flag@ are strongly recommended, since @IntEnum@ and @IntFlag@ break some semantic promises of an enumeration (by being comparable to integers, and thus by transitivity to other unrelated enumerations). |
---|
1667 | @IntEnum@ and @IntFlag@ should be used only in cases where @Enum@ and @Flag@ will not do; |
---|
1668 | for example, when integer constants are replaced with enumerations, or for interoperability with other systems. |
---|
1669 | |
---|
1670 | \subsection{Others} |
---|
1671 | |
---|
1672 | While @IntEnum@ is part of the enum module, it would be very simple to implement independently: |
---|
1673 | \begin{python} |
---|
1674 | class IntEnum(int, Enum): |
---|
1675 | pass |
---|
1676 | \end{python} |
---|
1677 | This demonstrates how similar derived enumerations can be defined; |
---|
1678 | for example a @FloatEnum@ that mixes in float instead of @int@. |
---|
1679 | |
---|
1680 | Some rules: |
---|
1681 | \begin{itemize} |
---|
1682 | \item |
---|
1683 | When subclassing @Enum@, mix-in types must appear before @Enum@ itself in the sequence of bases, as in the @IntEnum@ example above. |
---|
1684 | \item |
---|
1685 | Mix-in types must be subclassable. |
---|
1686 | For example, @bool@ and @range@ are not subclassable and will throw an error during Enum creation if used as the mix-in type. |
---|
1687 | \item |
---|
1688 | While @Enum@ can have members of any type, once you mix in an additional type, all the members must have values of that type, e.g. @int@ above. |
---|
1689 | This restriction does not apply to mix-ins which only add methods and don't specify another type. |
---|
1690 | \item |
---|
1691 | When another data type is mixed in, the value attribute is not the same as the enum member itself, although it is equivalent and will compare equal. |
---|
1692 | \item |
---|
1693 | A data type is a mixin that defines @__new__()@, or a @dataclass@ |
---|
1694 | \item |
---|
1695 | \%-style formatting: @%s@ and @%r@ call the @Enum@ class's @__str__()@ and @__repr__()@ respectively; other codes (such as @%i@ or @%h@ for @IntEnum@) treat the enum member as its mixed-in type. |
---|
1696 | \item |
---|
1697 | Formatted string literals, @str.format()@, and format() will use the enum's @__str__()@ method. |
---|
1698 | \end{itemize} |
---|
1699 | Note: Because @IntEnum@, @IntFlag@, and @StrEnum@ are designed to be drop-in replacements for existing constants, their @__str__()@ method has been reset to their data types' @__str__()@ method. |
---|
1700 | |
---|
1701 | \subsection{When to use \lstinline{__new__()} vs. \lstinline{__init__()}} |
---|
1702 | |
---|
1703 | @__new__()@ must be used whenever you want to customize the actual value of the @Enum@ member. |
---|
1704 | Any other modifications may go in either @__new__()@ or @__init__()@, with @__init__()@ being preferred. |
---|
1705 | |
---|
1706 | For example, if you want to pass several items to the constructor, but only want one of them to be the value: |
---|
1707 | \begin{python} |
---|
1708 | >>> class Coordinate(bytes, Enum): |
---|
1709 | ... """ |
---|
1710 | ... Coordinate with binary codes that can be indexed by the int code. |
---|
1711 | ... """ |
---|
1712 | ... def __new__(cls, value, label, unit): |
---|
1713 | ... obj = bytes.__new__(cls, [value]) |
---|
1714 | ... obj._value_ = value |
---|
1715 | ... obj.label = label |
---|
1716 | ... obj.unit = unit |
---|
1717 | ... return obj |
---|
1718 | ... PX = (0, 'P.X', 'km') |
---|
1719 | ... PY = (1, 'P.Y', 'km') |
---|
1720 | ... VX = (2, 'V.X', 'km/s') |
---|
1721 | ... VY = (3, 'V.Y', 'km/s') |
---|
1722 | |
---|
1723 | >>> print(Coordinate['PY']) |
---|
1724 | Coordinate.PY |
---|
1725 | |
---|
1726 | >>> print(Coordinate(3)) |
---|
1727 | Coordinate.VY |
---|
1728 | \end{python} |
---|
1729 | Warning: Do not call @super().__new__()@, as the lookup-only @__new__@ is the one that is found; instead, use the data type directly. |
---|
1730 | |
---|
1731 | \subsection{Finer Points} |
---|
1732 | |
---|
1733 | Supported @__dunder__@ names |
---|
1734 | |
---|
1735 | @__members__@ is a read-only ordered mapping of member\_name:member items. It is only available on the class. |
---|
1736 | |
---|
1737 | @__new__()@, if specified, must create and return the enum members; it is also a very good idea to set the member's @_value_@ appropriately. Once all the members are created it is no longer used. |
---|
1738 | Supported @_sunder_@ names |
---|
1739 | \begin{itemize} |
---|
1740 | \item |
---|
1741 | @_name_@ -- name of the member |
---|
1742 | \item |
---|
1743 | @_value_@ -- value of the member; can be set / modified in @__new__@ |
---|
1744 | \item |
---|
1745 | @_missing_@ -- a lookup function used when a value is not found; may be overridden |
---|
1746 | \item |
---|
1747 | @_ignore_@ -- a list of names, either as a @list@ or a @str@, that will not be transformed into members, and will be removed from the final class |
---|
1748 | \item |
---|
1749 | @_order_@ -- used in Python 2/3 code to ensure member order is consistent (class attribute, removed during class creation) |
---|
1750 | \item |
---|
1751 | @_generate_@next@_value_@ -- used by the Functional API and by @auto@ to get an appropriate value for an enum member; may be overridden |
---|
1752 | \end{itemize} |
---|
1753 | Note: For standard @Enum@ classes the next value chosen is the last value seen incremented by one. |
---|
1754 | |
---|
1755 | For @Flag@ classes the next value chosen will be the next highest power-of-two, regardless of the last value seen. |
---|
1756 | |
---|
1757 | New in version 3.6: @_missing_@, @_order_@, @_generate_@next@_value_@ |
---|
1758 | |
---|
1759 | New in version 3.7: @_ignore_@ |
---|
1760 | |
---|
1761 | To help keep Python 2 / Python 3 code in sync an @_order_@ attribute can be provided. |
---|
1762 | It will be checked against the actual order of the enumeration and raise an error if the two do not match: |
---|
1763 | \begin{python} |
---|
1764 | >>> class Color(Enum): |
---|
1765 | ... _order_ = 'RED GREEN BLUE' |
---|
1766 | ... RED = 1 |
---|
1767 | ... BLUE = 3 |
---|
1768 | ... GREEN = 2 |
---|
1769 | ... |
---|
1770 | Traceback (most recent call last): |
---|
1771 | ... |
---|
1772 | TypeError: member order does not match _order_: |
---|
1773 | ['RED', 'BLUE', 'GREEN'] |
---|
1774 | ['RED', 'GREEN', 'BLUE'] |
---|
1775 | \end{python} |
---|
1776 | Note: In Python 2 code the @_order_@ attribute is necessary as definition order is lost before it can be recorded. |
---|
1777 | |
---|
1778 | \subsection{\lstinline{_Private__names}} |
---|
1779 | |
---|
1780 | Private names are not converted to enum members, but remain normal attributes. |
---|
1781 | |
---|
1782 | Changed in version 3.11. |
---|
1783 | |
---|
1784 | \subsection{\lstinline{Enum} member type} |
---|
1785 | |
---|
1786 | @Enum@ members are instances of their enum class, and are normally accessed as @EnumClass.member@. |
---|
1787 | In certain situations, such as writing custom enum behavior, being able to access one member directly from another is useful, and is supported; |
---|
1788 | however, in order to avoid name clashes between member names and attributes/methods from mixed-in classes, upper-case names are strongly recommended. |
---|
1789 | |
---|
1790 | Changed in version 3.5. |
---|
1791 | |
---|
1792 | \subsection{Creating members that are mixed with other data types} |
---|
1793 | |
---|
1794 | When subclassing other data types, such as @int@ or @str@, with an @Enum@, all values after the = @are@ passed to that data type's constructor. For example: |
---|
1795 | \begin{python} |
---|
1796 | >>> class MyEnum(IntEnum): # help(int) -> int(x, base=10) -> integer |
---|
1797 | ... example = '11', 16 # so x='11' and base=16 |
---|
1798 | ... |
---|
1799 | MyEnum.example.value # and hex(11) is... |
---|
1800 | 17 |
---|
1801 | \end{python} |
---|
1802 | |
---|
1803 | \subsection{\lstinline{Boolean} value of \lstinline{Enum} classes and members} |
---|
1804 | |
---|
1805 | Enum classes that are mixed with non-@Enum@ types (such as @int@, @str@, etc.) are evaluated according to the mixed-in type's rules; |
---|
1806 | otherwise, all members evaluate as @True@. |
---|
1807 | To make your own enum's boolean evaluation depend on the member's value add the following to your class: |
---|
1808 | \begin{python} |
---|
1809 | def __bool__(self): |
---|
1810 | return bool(self.value) |
---|
1811 | \end{python} |
---|
1812 | Plain @Enum@ classes always evaluate as @True@. |
---|
1813 | |
---|
1814 | \subsection{\lstinline{Enum} classes with methods} |
---|
1815 | |
---|
1816 | If you give your enum subclass extra methods, like the Planet class below, those methods will show up in a dir() of the member, but not of the class: |
---|
1817 | \begin{python} |
---|
1818 | >>> dir(Planet) |
---|
1819 | ['EARTH', 'JUPITER', 'MARS', 'MERCURY', 'NEPTUNE', 'SATURN', 'URANUS', 'VENUS', |
---|
1820 | '__class__', '__doc__', '__members__', '__module__'] |
---|
1821 | >>> dir(Planet.EARTH) |
---|
1822 | ['__class__', '__doc__', '__module__', 'mass', 'name', 'radius', 'surface_gravity', 'value'] |
---|
1823 | \end{python} |
---|
1824 | |
---|
1825 | \subsection{Combining members of \lstinline{Flag}} |
---|
1826 | |
---|
1827 | Iterating over a combination of @Flag@ members will only return the members that are comprised of a single bit: |
---|
1828 | \begin{python} |
---|
1829 | >>> class Color(Flag): |
---|
1830 | ... RED = auto() |
---|
1831 | ... GREEN = auto() |
---|
1832 | ... BLUE = auto() |
---|
1833 | ... MAGENTA = RED | BLUE |
---|
1834 | ... YELLOW = RED | GREEN |
---|
1835 | ... CYAN = GREEN | BLUE |
---|
1836 | ... |
---|
1837 | >>> Color(3) # named combination |
---|
1838 | <Color.YELLOW: 3> |
---|
1839 | >>> Color(7) # not named combination |
---|
1840 | <Color.RED|GREEN|BLUE: 7> |
---|
1841 | \end{python} |
---|
1842 | |
---|
1843 | \subsection{\lstinline{Flag} and \lstinline{IntFlag} minutia} |
---|
1844 | |
---|
1845 | Using the following snippet for our examples: |
---|
1846 | \begin{python} |
---|
1847 | >>> class Color(IntFlag): |
---|
1848 | ... BLACK = 0 |
---|
1849 | ... RED = 1 |
---|
1850 | ... GREEN = 2 |
---|
1851 | ... BLUE = 4 |
---|
1852 | ... PURPLE = RED | BLUE |
---|
1853 | ... WHITE = RED | GREEN | BLUE |
---|
1854 | ... |
---|
1855 | \end{python} |
---|
1856 | the following are true: |
---|
1857 | \begin{itemize} |
---|
1858 | \item |
---|
1859 | single-bit flags are canonical |
---|
1860 | \item |
---|
1861 | multi-bit and zero-bit flags are aliases |
---|
1862 | \item |
---|
1863 | only canonical flags are returned during iteration: |
---|
1864 | \begin{python} |
---|
1865 | >>> list(Color.WHITE) |
---|
1866 | [<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 4>] |
---|
1867 | \end{python} |
---|
1868 | negating a flag or flag set returns a new flag/flag set with the corresponding positive integer value: |
---|
1869 | \begin{python} |
---|
1870 | >>> Color.BLUE |
---|
1871 | <Color.BLUE: 4> |
---|
1872 | |
---|
1873 | >>> ~Color.BLUE |
---|
1874 | <Color.RED|GREEN: 3> |
---|
1875 | \end{python} |
---|
1876 | \item |
---|
1877 | names of pseudo-flags are constructed from their members' names: |
---|
1878 | \begin{python} |
---|
1879 | >>> (Color.RED | Color.GREEN).name |
---|
1880 | 'RED|GREEN' |
---|
1881 | \end{python} |
---|
1882 | \item |
---|
1883 | multi-bit flags, aka aliases, can be returned from operations: |
---|
1884 | \begin{python} |
---|
1885 | >>> Color.RED | Color.BLUE |
---|
1886 | <Color.PURPLE: 5> |
---|
1887 | |
---|
1888 | >>> Color(7) # or Color(-1) |
---|
1889 | <Color.WHITE: 7> |
---|
1890 | |
---|
1891 | >>> Color(0) |
---|
1892 | <Color.BLACK: 0> |
---|
1893 | \end{python} |
---|
1894 | \item |
---|
1895 | membership / containment checking: zero-valued flags are always considered to be contained: |
---|
1896 | \begin{python} |
---|
1897 | >>> Color.BLACK in Color.WHITE |
---|
1898 | True |
---|
1899 | \end{python} |
---|
1900 | otherwise, only if all bits of one flag are in the other flag will True be returned: |
---|
1901 | \begin{python} |
---|
1902 | >>> Color.PURPLE in Color.WHITE |
---|
1903 | True |
---|
1904 | |
---|
1905 | >>> Color.GREEN in Color.PURPLE |
---|
1906 | False |
---|
1907 | \end{python} |
---|
1908 | \end{itemize} |
---|
1909 | There is a new boundary mechanism that controls how out-of-range / invalid bits are handled: @STRICT@, @CONFORM@, @EJECT@, and @KEEP@: |
---|
1910 | \begin{itemize} |
---|
1911 | \item |
---|
1912 | @STRICT@ --> raises an exception when presented with invalid values |
---|
1913 | \item |
---|
1914 | @CONFORM@ --> discards any invalid bits |
---|
1915 | \item |
---|
1916 | @EJECT@ --> lose Flag status and become a normal int with the given value |
---|
1917 | \item |
---|
1918 | @KEEP@ --> keep the extra bits |
---|
1919 | \begin{itemize} |
---|
1920 | \item |
---|
1921 | keeps Flag status and extra bits |
---|
1922 | \item |
---|
1923 | extra bits do not show up in iteration |
---|
1924 | \item |
---|
1925 | extra bits do show up in repr() and str() |
---|
1926 | \end{itemize} |
---|
1927 | \end{itemize} |
---|
1928 | The default for @Flag@ is @STRICT@, the default for @IntFlag@ is @EJECT@, and the default for @_convert_@ is @KEEP@ (see @ssl.Options@ for an example of when @KEEP@ is needed). |
---|
1929 | |
---|
1930 | \section{How are Enums and Flags different?} |
---|
1931 | |
---|
1932 | Enums have a custom metaclass that affects many aspects of both derived @Enum@ classes and their instances (members). |
---|
1933 | |
---|
1934 | \subsection{Enum Classes} |
---|
1935 | |
---|
1936 | The @EnumType@ metaclass is responsible for providing the @__contains__()@, @__dir__()@, @__iter__()@ and other methods that allow one to do things with an @Enum@ class that fail on a typical class, such as @list(Color)@ or @some_enum_var@ in @Color@. |
---|
1937 | @EnumType@ is responsible for ensuring that various other methods on the final @Enum@ class are correct (such as @__new__()@, @__getnewargs__()@, @__str__()@ and @__repr__()@). |
---|
1938 | |
---|
1939 | \subsection{Flag Classes} |
---|
1940 | |
---|
1941 | Flags have an expanded view of aliasing: to be canonical, the value of a flag needs to be a power-of-two value, and not a duplicate name. |
---|
1942 | So, in addition to the @Enum@ definition of alias, a flag with no value (a.k.a. 0) or with more than one power-of-two value (e.g. 3) is considered an alias. |
---|
1943 | |
---|
1944 | \subsection{Enum Members (aka instances)} |
---|
1945 | |
---|
1946 | The most interesting thing about enum members is that they are singletons. |
---|
1947 | @EnumType@ creates them all while it is creating the enum class itself, and then puts a custom @__new__()@ in place to ensure that no new ones are ever instantiated by returning only the existing member instances. |
---|
1948 | |
---|
1949 | \subsection{Flag Members} |
---|
1950 | |
---|
1951 | Flag members can be iterated over just like the @Flag@ class, and only the canonical members will be returned. |
---|
1952 | For example: |
---|
1953 | \begin{python} |
---|
1954 | >>> list(Color) |
---|
1955 | [<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 4>] |
---|
1956 | \end{python} |
---|
1957 | (Note that BLACK, PURPLE, and WHITE do not show up.) |
---|
1958 | |
---|
1959 | Inverting a flag member returns the corresponding positive value, rather than a negative value -- for example: |
---|
1960 | \begin{python} |
---|
1961 | >>> ~Color.RED |
---|
1962 | <Color.GREEN|BLUE: 6> |
---|
1963 | \end{python} |
---|
1964 | Flag members have a length corresponding to the number of power-of-two values they contain. For example: |
---|
1965 | \begin{python} |
---|
1966 | >>> len(Color.PURPLE) |
---|
1967 | 2 |
---|
1968 | \end{python} |
---|
1969 | |
---|
1970 | \subsection{Enum Cookbook} |
---|
1971 | |
---|
1972 | While @Enum@, @IntEnum@, @StrEnum@, @Flag@, and @IntFlag@ are expected to cover the majority of use-cases, they cannot cover them all. Here are recipes for some different types of enumerations that can be used directly, or as examples for creating one's own. |
---|
1973 | |
---|
1974 | \subsection{Omitting values} |
---|
1975 | |
---|
1976 | In many use-cases, one doesn't care what the actual value of an enumeration is. There are several ways to define this type of simple enumeration: |
---|
1977 | \begin{itemize} |
---|
1978 | \item |
---|
1979 | use instances of auto for the value |
---|
1980 | \item |
---|
1981 | use instances of object as the value |
---|
1982 | \item |
---|
1983 | use a descriptive string as the value |
---|
1984 | \item |
---|
1985 | use a tuple as the value and a custom @__new__()@ to replace the tuple with an @int@ value |
---|
1986 | \end{itemize} |
---|
1987 | Using any of these methods signifies to the user that these values are not important, and also enables one to add, remove, or reorder members without having to renumber the remaining members. |
---|
1988 | |
---|
1989 | \subsection{Using \lstinline{auto}} |
---|
1990 | |
---|
1991 | Using @auto@ would look like: |
---|
1992 | \begin{python} |
---|
1993 | >>> class Color(Enum): |
---|
1994 | ... RED = auto() |
---|
1995 | ... BLUE = auto() |
---|
1996 | ... GREEN = auto() |
---|
1997 | ... |
---|
1998 | >>> Color.GREEN |
---|
1999 | <Color.GREEN: 3> |
---|
2000 | \end{python} |
---|
2001 | |
---|
2002 | \subsection{Using \lstinline{object}} |
---|
2003 | |
---|
2004 | Using @object@ would look like: |
---|
2005 | \begin{python} |
---|
2006 | >>> class Color(Enum): |
---|
2007 | ... RED = object() |
---|
2008 | ... GREEN = object() |
---|
2009 | ... BLUE = object() |
---|
2010 | ... |
---|
2011 | >>> Color.GREEN |
---|
2012 | <Color.GREEN: <object object at 0x...>> |
---|
2013 | \end{python} |
---|
2014 | This is also a good example of why you might want to write your own @__repr__()@: |
---|
2015 | \begin{python} |
---|
2016 | >>> class Color(Enum): |
---|
2017 | ... RED = object() |
---|
2018 | ... GREEN = object() |
---|
2019 | ... BLUE = object() |
---|
2020 | ... def __repr__(self): |
---|
2021 | ... return "<%s.%s>" % (self.__class__.__name__, self._name_) |
---|
2022 | ... |
---|
2023 | >>> Color.GREEN |
---|
2024 | <Color.GREEN> |
---|
2025 | \end{python} |
---|
2026 | |
---|
2027 | \subsection{Using a descriptive string} |
---|
2028 | |
---|
2029 | Using a string as the value would look like: |
---|
2030 | \begin{python} |
---|
2031 | >>> class Color(Enum): |
---|
2032 | ... RED = 'stop' |
---|
2033 | ... GREEN = 'go' |
---|
2034 | ... BLUE = 'too fast!' |
---|
2035 | ... |
---|
2036 | >>> Color.GREEN |
---|
2037 | <Color.GREEN: 'go'> |
---|
2038 | \end{python} |
---|
2039 | |
---|
2040 | \subsection{Using a custom \lstinline{__new__()}} |
---|
2041 | |
---|
2042 | Using an auto-numbering @__new__()@ would look like: |
---|
2043 | \begin{python} |
---|
2044 | >>> class AutoNumber(Enum): |
---|
2045 | ... def __new__(cls): |
---|
2046 | ... value = len(cls.__members__) + 1 |
---|
2047 | ... obj = object.__new__(cls) |
---|
2048 | ... obj._value_ = value |
---|
2049 | ... return obj |
---|
2050 | ... |
---|
2051 | >>> class Color(AutoNumber): |
---|
2052 | ... RED = () |
---|
2053 | ... GREEN = () |
---|
2054 | ... BLUE = () |
---|
2055 | ... |
---|
2056 | >>> Color.GREEN |
---|
2057 | <Color.GREEN: 2> |
---|
2058 | \end{python} |
---|
2059 | To make a more general purpose @AutoNumber@, add @*args@ to the signature: |
---|
2060 | \begin{python} |
---|
2061 | >>> class AutoNumber(Enum): |
---|
2062 | ... def __new__(cls, *args): # this is the only change from above |
---|
2063 | ... value = len(cls.__members__) + 1 |
---|
2064 | ... obj = object.__new__(cls) |
---|
2065 | ... obj._value_ = value |
---|
2066 | ... return obj |
---|
2067 | \end{python} |
---|
2068 | Then when you inherit from @AutoNumber@ you can write your own @__init__@ to handle any extra arguments: |
---|
2069 | \begin{python} |
---|
2070 | >>> class Swatch(AutoNumber): |
---|
2071 | ... def __init__(self, pantone='unknown'): |
---|
2072 | ... self.pantone = pantone |
---|
2073 | ... AUBURN = '3497' |
---|
2074 | ... SEA_GREEN = '1246' |
---|
2075 | ... BLEACHED_CORAL = () # New color, no Pantone code yet! |
---|
2076 | ... |
---|
2077 | >>> Swatch.SEA_GREEN |
---|
2078 | <Swatch.SEA_GREEN: 2> |
---|
2079 | >>> Swatch.SEA_GREEN.pantone |
---|
2080 | '1246' |
---|
2081 | >>> Swatch.BLEACHED_CORAL.pantone |
---|
2082 | 'unknown' |
---|
2083 | \end{python} |
---|
2084 | Note: The @__new__()@ method, if defined, is used during creation of the Enum members; |
---|
2085 | it is then replaced by Enum's @__new__()@ which is used after class creation for lookup of existing members. |
---|
2086 | |
---|
2087 | Warning: Do not call @super().__new__()@, as the lookup-only @__new__@ is the one that is found; |
---|
2088 | instead, use the data type directly -- e.g.: |
---|
2089 | \begin{python} |
---|
2090 | obj = int.__new__(cls, value) |
---|
2091 | \end{python} |
---|
2092 | |
---|
2093 | \subsection{OrderedEnum} |
---|
2094 | |
---|
2095 | An ordered enumeration that is not based on @IntEnum@ and so maintains the normal @Enum@ invariants (such as not being comparable to other enumerations): |
---|
2096 | \begin{python} |
---|
2097 | >>> class OrderedEnum(Enum): |
---|
2098 | ... def __ge__(self, other): |
---|
2099 | ... if self.__class__ is other.__class__: |
---|
2100 | ... return self.value >= other.value |
---|
2101 | ... return NotImplemented |
---|
2102 | ... def __gt__(self, other): |
---|
2103 | ... if self.__class__ is other.__class__: |
---|
2104 | ... return self.value > other.value |
---|
2105 | ... return NotImplemented |
---|
2106 | ... def __le__(self, other): |
---|
2107 | ... if self.__class__ is other.__class__: |
---|
2108 | ... return self.value <= other.value |
---|
2109 | ... return NotImplemented |
---|
2110 | ... def __lt__(self, other): |
---|
2111 | ... if self.__class__ is other.__class__: |
---|
2112 | ... return self.value < other.value |
---|
2113 | ... return NotImplemented |
---|
2114 | ... |
---|
2115 | >>> class Grade(OrderedEnum): |
---|
2116 | ... A = 5 |
---|
2117 | ... B = 4 |
---|
2118 | ... C = 3 |
---|
2119 | ... D = 2 |
---|
2120 | ... F = 1 |
---|
2121 | >>> Grade.C < Grade.A |
---|
2122 | True |
---|
2123 | \end{python} |
---|
2124 | |
---|
2125 | \subsection{DuplicateFreeEnum} |
---|
2126 | |
---|
2127 | Raises an error if a duplicate member value is found instead of creating an alias: |
---|
2128 | \begin{python} |
---|
2129 | >>> class DuplicateFreeEnum(Enum): |
---|
2130 | ... def __init__(self, *args): |
---|
2131 | ... cls = self.__class__ |
---|
2132 | ... if any(self.value == e.value for e in cls): |
---|
2133 | ... a = self.name |
---|
2134 | ... e = cls(self.value).name |
---|
2135 | ... raise ValueError( |
---|
2136 | ... "aliases not allowed in DuplicateFreeEnum: %r --> %r" |
---|
2137 | ... % (a, e)) |
---|
2138 | >>> class Color(DuplicateFreeEnum): |
---|
2139 | ... RED = 1 |
---|
2140 | ... GREEN = 2 |
---|
2141 | ... BLUE = 3 |
---|
2142 | ... GRENE = 2 |
---|
2143 | ... |
---|
2144 | Traceback (most recent call last): |
---|
2145 | ... |
---|
2146 | ValueError: aliases not allowed in DuplicateFreeEnum: 'GRENE' --> 'GREEN' |
---|
2147 | \end{python} |
---|
2148 | Note: This is a useful example for subclassing Enum to add or change other behaviors as well as disallowing aliases. |
---|
2149 | If the only desired change is disallowing aliases, the @unique()@ decorator can be used instead. |
---|
2150 | |
---|
2151 | \subsection{Planet} |
---|
2152 | |
---|
2153 | If @__new__()@ or @__init__()@ is defined, the value of the enum member will be passed to those methods: |
---|
2154 | \begin{figure} |
---|
2155 | \begin{python} |
---|
2156 | from enum import Enum |
---|
2157 | class Planet(Enum): |
---|
2158 | MERCURY = ( 3.303E23, 2.4397E6 ) |
---|
2159 | VENUS = ( 4.869E24, 6.0518E6 ) |
---|
2160 | EARTH = (5.976E24, 6.37814E6) |
---|
2161 | MARS = (6.421E23, 3.3972E6) |
---|
2162 | JUPITER = (1.9E27, 7.1492E7) |
---|
2163 | SATURN = (5.688E26, 6.0268E7) |
---|
2164 | URANUS = (8.686E25, 2.5559E7) |
---|
2165 | NEPTUNE = (1.024E26, 2.4746E7) |
---|
2166 | def __init__( self, mass, radius ): |
---|
2167 | self.mass = mass # in kilograms |
---|
2168 | self.radius = radius # in meters |
---|
2169 | def surface_gravity( self ): |
---|
2170 | # universal gravitational constant (m3 kg-1 s-2) |
---|
2171 | G = 6.67300E-11 |
---|
2172 | return G * self.mass / (self.radius * self.radius) |
---|
2173 | for p in Planet: |
---|
2174 | print( f"{p.name}: {p.value}" ) |
---|
2175 | |
---|
2176 | MERCURY: (3.303e+23, 2439700.0) |
---|
2177 | VENUS: (4.869e+24, 6051800.0) |
---|
2178 | EARTH: (5.976e+24, 6378140.0) |
---|
2179 | MARS: (6.421e+23, 3397200.0) |
---|
2180 | JUPITER: (1.9e+27, 71492000.0) |
---|
2181 | SATURN: (5.688e+26, 60268000.0) |
---|
2182 | URANUS: (8.686e+25, 25559000.0) |
---|
2183 | NEPTUNE: (1.024e+26, 24746000.0) |
---|
2184 | \end{python} |
---|
2185 | \caption{Python Planet Example} |
---|
2186 | \label{f:PythonPlanetExample} |
---|
2187 | \end{figure} |
---|
2188 | |
---|
2189 | |
---|
2190 | \subsection{TimePeriod} |
---|
2191 | |
---|
2192 | An example to show the @_ignore_@ attribute in use: |
---|
2193 | \begin{python} |
---|
2194 | >>> from datetime import timedelta |
---|
2195 | >>> class Period(timedelta, Enum): |
---|
2196 | ... "different lengths of time" |
---|
2197 | ... _ignore_ = 'Period i' |
---|
2198 | ... Period = vars() |
---|
2199 | ... for i in range(367): |
---|
2200 | ... Period['day_%d' % i] = i |
---|
2201 | ... |
---|
2202 | >>> list(Period)[:2] |
---|
2203 | [<Period.day_0: datetime.timedelta(0)>, <Period.day_1: datetime.timedelta(days=1)>] |
---|
2204 | >>> list(Period)[-2:] |
---|
2205 | [<Period.day_365: datetime.timedelta(days=365)>, <Period.day_366: datetime.timedelta(days=366)>] |
---|
2206 | \end{python} |
---|
2207 | |
---|
2208 | \subsection{Subclassing EnumType} |
---|
2209 | |
---|
2210 | While most enum needs can be met by customizing @Enum@ subclasses, either with class decorators or custom functions, @EnumType@ can be subclassed to provide a different Enum experience. |
---|
2211 | |
---|
2212 | |
---|
2213 | \section{OCaml} |
---|
2214 | \lstnewenvironment{ocaml}[1][]{\lstset{language=OCaml,escapechar=\$,moredelim=**[is][\color{red}]{@}{@},}\lstset{#1}}{} |
---|
2215 | |
---|
2216 | % https://ocaml.org/docs/basic-data-types#enumerated-data-types |
---|
2217 | % https://dev.realworldocaml.org/runtime-memory-layout.html |
---|
2218 | |
---|
2219 | OCaml provides a variant (union) type, where multiple heterogeneously-typed objects share the same storage. |
---|
2220 | The simplest form of the variant type is a list of nullary datatype constructors, which is like an unscoped, pure enumeration. |
---|
2221 | |
---|
2222 | (I think the value of a ocaml variants are types not object, so I am not sure about this line) |
---|
2223 | OCaml provides a variant (union) type, which is an aggregation of heterogeneous types. |
---|
2224 | A basic variant is a list of nullary datatype constructors, which is like an unscoped, pure enumeration. |
---|
2225 | \begin{ocaml} |
---|
2226 | type weekday = Mon | Tue | Wed | Thu | Fri | Sat | Sun |
---|
2227 | let day : weekday @= Mon@ $\C{(* bind *)}$ |
---|
2228 | let take_class( d : weekday ) = |
---|
2229 | @match@ d with $\C{(* matching *)}$ |
---|
2230 | Mon | Wed -> Printf.printf "CS442\n" | |
---|
2231 | Tue | Thu -> Printf.printf "CS343\n" | |
---|
2232 | Fri -> Printf.printf "Tutorial\n" | |
---|
2233 | _ -> Printf.printf "Take a break\n" |
---|
2234 | let _ = take_class( Mon ); |
---|
2235 | @CS442@ |
---|
2236 | \end{ocaml} |
---|
2237 | The only operations are binding and pattern matching (equality), where the variant name is logically the implementation tag stored in the union for discriminating the value in the object storage. |
---|
2238 | OCaml compile store tags as ascending int, starting from 0. Variants @Mon@ to @Sun@ are stored as int value 0 to 6. |
---|
2239 | Here, function @take_class@ has a @weekday@ parameter, and returns @"CS442"@, if the weekday value is @Mon@ or @Wed@, @"CS343"@, if the value is @Tue@ or @Thu@, and @"Tutorial"@ for @Fri@. |
---|
2240 | The ``@_@'' is a wildcard matching any @weekday@ value, so the function returns @"Take a break"@ for values @Sat@ or @Sun@, which are not matched by the previous cases. |
---|
2241 | Since the variant has no type, it has a \Newterm{0-arity constructor}, \ie no parameters. |
---|
2242 | Because @weekday@ is a union of values @Mon@ to @Sun@, it is a \Newterm{union type} in turns of the functional-programming paradigm. |
---|
2243 | |
---|
2244 | Each variant can have an associated heterogeneous type, with an n-ary constructor for creating a corresponding value. |
---|
2245 | \begin{ocaml} |
---|
2246 | type colour = Red | Green of @string@ | Blue of @int * float@ |
---|
2247 | \end{ocaml} |
---|
2248 | A variant with parameter is stored in a memory block, prefixed by an int tag and has its parameters stores as words in the block. |
---|
2249 | @colour@ is a summation of a nullary type, a unary product type of @string@, and a cross product of @int@ and @float@. |
---|
2250 | (Mathematically, a @Blue@ value is a Cartesian product of the types @int@ type and @float@.) |
---|
2251 | Hence, a variant type creates a sum of product of different types. |
---|
2252 | \begin{ocaml} |
---|
2253 | let c = Red $\C{(* 0-ary constructor, set tag *)}$ |
---|
2254 | let _ = match c with Red -> Printf.printf "Red, " |
---|
2255 | let c = Green( "abc" ) $\C{(* 1-ary constructor, set tag *)}$ |
---|
2256 | let _ = match c with Green g -> Printf.printf "%s, " g |
---|
2257 | let c = Blue( 1, 1.5 ) $\C{(* 2-ary constructor, set tag *)}$ |
---|
2258 | let _ = match c with Blue( i, f ) -> Printf.printf "%d %g\n" i f |
---|
2259 | @Red, abc, 1 1.5@ |
---|
2260 | \end{ocaml} |
---|
2261 | |
---|
2262 | |
---|
2263 | A variant type can have a recursive definition. |
---|
2264 | \begin{ocaml} |
---|
2265 | type @stringList@ = Empty | Pair of string * @stringList@ |
---|
2266 | \end{ocaml} |
---|
2267 | which is a recursive sum of product of types, called an \Newterm{algebraic data-type}. |
---|
2268 | A recursive function is often used to pattern match against a recursive variant type. |
---|
2269 | \begin{ocaml} |
---|
2270 | let rec @len_of_string_list@( list : stringList ): int = |
---|
2271 | match list with |
---|
2272 | Empty -> 0 | |
---|
2273 | Pair( _ , r ) -> 1 + @len_of_string_list@ r |
---|
2274 | \end{ocaml} |
---|
2275 | Here, the head of the recursive type is removed and the remainder is processed until the type is empty. |
---|
2276 | Each recursion is counted to obtain the number of elements in the type. |
---|
2277 | |
---|
2278 | Note, the compiler statically guarantees that only the correct kind of type is used in the \lstinline[language=OCaml]{match} statement. |
---|
2279 | However, the union tag is dynamically set on binding (and possible reset on assignment), so a \lstinline[language=OCaml]{match} statement is effectively doing RTTI to select the matching case clause. |
---|
2280 | |
---|
2281 | In summary, an OCaml variant is a singleton value rather than a set of possibly ordered values, and hence, has no notion of enumerabilty. |
---|
2282 | Therefore it is not an enumeration, except for the simple pure (nullary) case. |
---|
2283 | |
---|
2284 | \begin{comment} |
---|
2285 | Date: Wed, 13 Mar 2024 10:52:34 -0400 |
---|
2286 | Subject: Re: OCaml |
---|
2287 | To: "Peter A. Buhr" <pabuhr@uwaterloo.ca> |
---|
2288 | From: Gregor Richards <gregor.richards@uwaterloo.ca> |
---|
2289 | |
---|
2290 | On 3/12/24 18:34, Peter A. Buhr wrote: |
---|
2291 | > Gregor, attached is a section Jiada wrote on OCaml (1-page). |
---|
2292 | > Does it reflect our discussion about functional languages and enumerations? |
---|
2293 | |
---|
2294 | Yeah, I think so. The most important part, i.e., that once they're |
---|
2295 | parameterized they're not really enumerations at all, is covered clearly |
---|
2296 | enough. |
---|
2297 | |
---|
2298 | A couple quibbles: |
---|
2299 | |
---|
2300 | <<a list of untyped tags>> |
---|
2301 | |
---|
2302 | This is true, but leaking implementation details. These are nullary datatype |
---|
2303 | constructors. Indeed, you later talk about "tagged variants", which are really |
---|
2304 | just parameterized variants, using the term "tag" differently, confusing the |
---|
2305 | term "tag" further. |
---|
2306 | |
---|
2307 | <<Because weekday is a summation of values Mon to Sun, it is a sum type in |
---|
2308 | turns of the functional-programming paradigm>> |
---|
2309 | |
---|
2310 | It is a *union* of values and is a *union* type. |
---|
2311 | |
---|
2312 | With valediction, |
---|
2313 | - Gregor Richards |
---|
2314 | |
---|
2315 | |
---|
2316 | Date: Thu, 14 Mar 2024 21:45:52 -0400 |
---|
2317 | Subject: Re: OCaml "enums" do come with ordering |
---|
2318 | To: "Peter A. Buhr" <pabuhr@uwaterloo.ca> |
---|
2319 | From: Gregor Richards <gregor.richards@uwaterloo.ca> |
---|
2320 | |
---|
2321 | On 3/14/24 21:30, Peter A. Buhr wrote: |
---|
2322 | > I've marked 3 places with your name to shows places with enum ordering. |
---|
2323 | > |
---|
2324 | > type weekday = Mon | Tue | Wed | Thu | Fri | Sat | Sun |
---|
2325 | > let day : weekday = Mon |
---|
2326 | > let take_class( d : weekday ) = |
---|
2327 | > if d <= Fri then (* Gregor *) |
---|
2328 | > Printf.printf "weekday\n" |
---|
2329 | > else if d >= Sat then (* Gregor *) |
---|
2330 | > Printf.printf "weekend\n"; |
---|
2331 | > match d with |
---|
2332 | > Mon | Wed -> Printf.printf "CS442\n" | |
---|
2333 | > Tue | Thu -> Printf.printf "CS343\n" | |
---|
2334 | > Fri -> Printf.printf "Tutorial\n" | |
---|
2335 | > _ -> Printf.printf "Take a break\n" |
---|
2336 | > |
---|
2337 | > let _ = take_class( Mon ); take_class( Sat ); |
---|
2338 | > |
---|
2339 | > type colour = Red | Green of string | Blue of int * float |
---|
2340 | > let c = Red |
---|
2341 | > let _ = match c with Red -> Printf.printf "Red, " |
---|
2342 | > let c = Green( "abc" ) |
---|
2343 | > let _ = match c with Green g -> Printf.printf "%s, " g |
---|
2344 | > let c = Blue( 1, 1.5 ) |
---|
2345 | > let _ = match c with Blue( i, f ) -> Printf.printf "%d %g\n" i f |
---|
2346 | > |
---|
2347 | > let check_colour(c: colour): string = |
---|
2348 | > if c < Green( "xyz" ) then (* Gregor *) |
---|
2349 | > Printf.printf "green\n"; |
---|
2350 | > match c with |
---|
2351 | > Red -> "Red" | |
---|
2352 | > Green g -> g | |
---|
2353 | > Blue(i, f) -> string_of_int i ^ string_of_float f |
---|
2354 | > let _ = check_colour( Red ); check_colour( Green( "xyz" ) ); |
---|
2355 | > |
---|
2356 | > type stringList = Empty | Pair of string * stringList |
---|
2357 | > let rec len_of_string_list(l: stringList): int = |
---|
2358 | > match l with |
---|
2359 | > Empty -> 0 | |
---|
2360 | > Pair(_ , r) -> 1 + len_of_string_list r |
---|
2361 | > |
---|
2362 | > let _ = for i = 1 to 10 do |
---|
2363 | > Printf.printf "%d, " i |
---|
2364 | > done |
---|
2365 | > |
---|
2366 | > (* Local Variables: *) |
---|
2367 | > (* tab-width: 4 *) |
---|
2368 | > (* compile-command: "ocaml test.ml" *) |
---|
2369 | > (* End: *) |
---|
2370 | |
---|
2371 | My functional-language familiarity is far more with Haskell than OCaml. I |
---|
2372 | mostly view OCaml through a lens of "it's Haskell but with cheating". Haskell |
---|
2373 | "enums" (ADTs) aren't ordered unless you specifically and manually put them in |
---|
2374 | the Ord typeclass by defining the comparators. Apparently, OCaml has some |
---|
2375 | other rule, which I would guess is something like "sort by tag then by order of |
---|
2376 | parameter". Having a default behavior for comparators is *bizarre*; my guess |
---|
2377 | would be that it gained this behavior in its flirtation with object |
---|
2378 | orientation, but that's just a guess (and irrelevant). |
---|
2379 | |
---|
2380 | This gives a total order, but not enumerability (which would still be |
---|
2381 | effectively impossible or even meaningless since enums are just a special case |
---|
2382 | of ADTs). |
---|
2383 | |
---|
2384 | With valediction, |
---|
2385 | - Gregor Richards |
---|
2386 | |
---|
2387 | Date: Wed, 20 Mar 2024 18:16:44 -0400 |
---|
2388 | Subject: Re: |
---|
2389 | To: "Peter A. Buhr" <pabuhr@uwaterloo.ca> |
---|
2390 | From: Gregor Richards <gregor.richards@uwaterloo.ca> |
---|
2391 | |
---|
2392 | |
---|
2393 | On 3/20/24 17:26, Peter A. Buhr wrote: |
---|
2394 | > Gregor, everyone at this end would like a definition of "enumerability". Can |
---|
2395 | > you formulate one? |
---|
2396 | |
---|
2397 | According to the OED (emphasis added to the meaning I'm after): |
---|
2398 | |
---|
2399 | enumerate (verb, transitive). To count, ascertain the number of; **more |
---|
2400 | usually, to mention (a number of things or persons) separately, as if for the |
---|
2401 | purpose of counting**; to specify as in a list or catalogue. |
---|
2402 | |
---|
2403 | With C enums, if you know the lowest and highest value, you can simply loop |
---|
2404 | over them in a for loop (this is, of course, why so many enums come with an |
---|
2405 | ENUM_WHATEVER_LAST value). But, I would be hesitant to use the word "loop" to |
---|
2406 | describe enumerability, since in functional languages, you would recurse for |
---|
2407 | such a purpose. |
---|
2408 | |
---|
2409 | In Haskell, in order to do something with every member of an "enumeration", you |
---|
2410 | would have to explicitly list them all. The type system will help a bit since |
---|
2411 | it knows if you haven't listed them all, but you would have to statically have |
---|
2412 | every element in the enumeration. If somebody added new elements to the |
---|
2413 | enumeration later, your code to enumerate over them would no longer work |
---|
2414 | correctly, because you can't simply say "for each member of this enumeration do |
---|
2415 | X". In Haskell that's because there aren't actually enumerations; what they use |
---|
2416 | as enumerations are a degenerate form of algebraic datatypes, and ADTs are |
---|
2417 | certainly not enumerable. In OCaml, you've demonstrated that they impose |
---|
2418 | comparability, but I would still assume that you can't make a loop over every |
---|
2419 | member of an enumeration. (But, who knows!) |
---|
2420 | |
---|
2421 | Since that's literally what "enumerate" means, it seems like a rather important |
---|
2422 | property for enumerations to have ;) |
---|
2423 | |
---|
2424 | With valediction, |
---|
2425 | - Gregor Richards |
---|
2426 | |
---|
2427 | |
---|
2428 | From: Andrew James Beach <ajbeach@uwaterloo.ca> |
---|
2429 | To: Gregor Richards <gregor.richards@uwaterloo.ca>, Peter Buhr <pabuhr@uwaterloo.ca> |
---|
2430 | CC: Michael Leslie Brooks <mlbrooks@uwaterloo.ca>, Fangren Yu <f37yu@uwaterloo.ca>, |
---|
2431 | Jiada Liang <j82liang@uwaterloo.ca> |
---|
2432 | Subject: Re: Re: |
---|
2433 | Date: Thu, 21 Mar 2024 14:26:36 +0000 |
---|
2434 | |
---|
2435 | Does this mean that not all enum declarations in C create enumerations? If you |
---|
2436 | declare an enumeration like: |
---|
2437 | |
---|
2438 | enum Example { |
---|
2439 | Label, |
---|
2440 | Name = 10, |
---|
2441 | Tag = 3, |
---|
2442 | }; |
---|
2443 | |
---|
2444 | I don't think there is any way to enumerate (iterate, loop, recurse) over these |
---|
2445 | values without listing all of them. |
---|
2446 | |
---|
2447 | |
---|
2448 | Date: Thu, 21 Mar 2024 10:31:49 -0400 |
---|
2449 | Subject: Re: |
---|
2450 | To: Andrew James Beach <ajbeach@uwaterloo.ca>, Peter Buhr <pabuhr@uwaterloo.ca> |
---|
2451 | CC: Michael Leslie Brooks <mlbrooks@uwaterloo.ca>, Fangren Yu <f37yu@uwaterloo.ca>, |
---|
2452 | Jiada Liang <j82liang@uwaterloo.ca> |
---|
2453 | From: Gregor Richards <gregor.richards@uwaterloo.ca> |
---|
2454 | |
---|
2455 | I consider this conclusion reasonable. C enums can be nothing more than const |
---|
2456 | ints, and if used in that way, I personally wouldn't consider them as |
---|
2457 | enumerations in any meaningful sense, particularly since the type checker |
---|
2458 | essentially does nothing for you there. Then they're a way of writing consts |
---|
2459 | repeatedly with some textual indicator that these definitions are related; more |
---|
2460 | namespace, less enum. |
---|
2461 | |
---|
2462 | When somebody writes bitfield members as an enum, is that *really* an |
---|
2463 | enumeration, or just a use of the syntax for enums to keep related definitions |
---|
2464 | together? |
---|
2465 | |
---|
2466 | With valediction, |
---|
2467 | - Gregor Richards |
---|
2468 | \end{comment} |
---|
2469 | |
---|
2470 | |
---|
2471 | \section{Comparison} |
---|
2472 | |
---|
2473 | \VRef[Table]{t:FeatureLanguageComparison} shows a comparison of enumeration features and programming languages. |
---|
2474 | The features are high level and may not capture nuances within a particular language |
---|
2475 | The @const@ feature is simple macros substitution and not a typed enumeration. |
---|
2476 | |
---|
2477 | \begin{table} |
---|
2478 | \caption{Enumeration Feature / Language Comparison} |
---|
2479 | \label{t:FeatureLanguageComparison} |
---|
2480 | \small |
---|
2481 | \setlength{\tabcolsep}{3pt} |
---|
2482 | \newcommand{\CM}{\checkmark} |
---|
2483 | \begin{tabular}{r|c|c|c|c|c|c|c|c|c|c|c|c|c} |
---|
2484 | &Pascal & Ada &\Csharp& OCaml & Java &Modula-3&Golang& Rust & Swift & Python& C & \CC & \CFA \\ |
---|
2485 | \hline |
---|
2486 | @const@ & \CM & & & & & & \CM & & & & & \CM & \\ |
---|
2487 | \hline |
---|
2488 | \hline |
---|
2489 | pure & & & & & & & & & & & & & \CM \\ |
---|
2490 | \hline |
---|
2491 | typed & & & & & & & & & & & @int@ & integral & @T@ \\ |
---|
2492 | \hline |
---|
2493 | safe & & & & & & & & & & & & \CM & \CM \\ |
---|
2494 | \hline |
---|
2495 | ordered & & & & & & & & & & & \CM & \CM & \CM \\ |
---|
2496 | \hline |
---|
2497 | dup. values & & & & & & & & & & alias & \CM & \CM & \CM \\ |
---|
2498 | \hline |
---|
2499 | setable & & & & & & & & & & & \CM & \CM & \CM \\ |
---|
2500 | \hline |
---|
2501 | auto-init & & & & & & & & & & & \CM & \CM & \CM \\ |
---|
2502 | \hline |
---|
2503 | (un)scoped & & & & & & & & & & & U & U/S & U/S \\ |
---|
2504 | \hline |
---|
2505 | overload & & \CM & & & & & & & & & & \CM & \CM \\ |
---|
2506 | \hline |
---|
2507 | switch & & & & & & & & & & & \CM & \CM & \CM \\ |
---|
2508 | \hline |
---|
2509 | loop & & & & & & & & & & & & & \CM \\ |
---|
2510 | \hline |
---|
2511 | array & & & & & & & & & & & \CM & & \CM \\ |
---|
2512 | \hline |
---|
2513 | subtype & & & & & & & & & & & & & \CM \\ |
---|
2514 | \hline |
---|
2515 | inheritance & & & & & & & & & & & & & \CM \\ |
---|
2516 | \end{tabular} |
---|
2517 | \end{table} |
---|