Skip to content

Commit 5f0e358

Browse files
committed
Document enums (alongside collections)
Signed-off-by: Chris Warrick <kwpolska@gmail.com>
1 parent af1092c commit 5f0e358

1 file changed

Lines changed: 64 additions & 2 deletions

File tree

collections.rst

Lines changed: 64 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ The ones which we will talk about are:
1111
- ``counter``
1212
- ``deque``
1313
- ``namedtuple``
14+
- ``enum.Enum`` (outside of the module; Python 3.4+)
1415

1516
1.\ ``defaultdict``
1617
^^^^^^^^^^^^^^^^^^^
@@ -277,7 +278,68 @@ Like this:
277278
from collections import namedtuple
278279
279280
Animal = namedtuple('Animal', 'name age type')
280-
perry = Animal(name="perry", age=31, type="cat")
281+
perry = Animal(name="Perry", age=31, type="cat")
281282
print(perry._asdict())
282-
# Output: OrderedDict([('name', 'perry'), ('age', 31), ...
283+
# Output: OrderedDict([('name', 'Perry'), ('age', 31), ...
284+
285+
5.\ ``enum.Enum`` (Python 3.4+)
286+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
287+
288+
Another useful collection is the enum object. It is available in the ``enum``
289+
module, in Python 3.4 and up (also available as a backport in PyPI named ``enum34``.)
290+
Enums (`enumerated type <https://en.wikipedia.org/wiki/Enumerated_type>`) are
291+
basically a way to organize various things.
292+
293+
Let’s consider the Animal namedtuple from the last example. It had a ``type``
294+
field. The problem is, the type was a string. This poses some problems for
295+
us. What if the user types in ``Cat`` because they held the Shift key? Or
296+
``CAT``? Or ``kitten``?
297+
298+
Enumerations can help us avoid this problem, by not using strings. Consider
299+
this example:
300+
301+
.. code:: python
302+
303+
from collections import namedtuple
304+
from enum import Enum
305+
306+
class Species(Enum):
307+
cat = 1
308+
dog = 2
309+
horse = 3
310+
aardvark = 4
311+
butterfly = 5
312+
owl = 6
313+
platypus = 7
314+
dragon = 8
315+
unicorn = 9
316+
# The list goes on and on...
317+
318+
# But we don't really care about age, so we can use an alias.
319+
kitten = 1
320+
puppy = 2
321+
322+
Animal = namedtuple('Animal', 'name age type')
323+
perry = Animal(name="Perry", age=31, type=Species.cat)
324+
drogon = Animal(name="Drogon", age=4, type=Species.dragon)
325+
tom = Animal(name="Tom", age=75, type=Species.cat)
326+
charlie = Animal(name="Charlie", age=2, type=Species.kitten)
327+
328+
# And now, some tests.
329+
>>> charlie.type == tom.type
330+
True
331+
>>> charlie.type
332+
<Species.cat: 1>
333+
334+
335+
This is much less error-prone. We have to be specific, and we should use only
336+
the enumeration to name types.
337+
338+
There are three ways to access enumeration members. For example, all three
339+
methods will get you the value for ``cat``:
340+
341+
.. code:: python
283342
343+
Species(1)
344+
Species['cat']
345+
Species.cat

0 commit comments

Comments
 (0)