Python 3, an Illustrated Tour Transcripts
Chapter: The standard library
Lecture: Walk-through: Enum

Login or purchase this course to watch this video and the rest of the course contents.
0:00 We're going to look at the enum test file, open that up, we'll see that at the top here we've got a red, green and blue variable defined
0:08 and we've got a function here that's testing that whatever is passed in is equal to these variables. This is prime candidate to replace with enum.
0:15 Let's look at what it says to do. Create an enumeration color that has red, green and blue
0:21 as the different members, use the class style by subclassing enum. And in parentheses, normally these are created at the global level.
0:28 Let's import the enum class, that's in the standard library these days. I'm going to say from the enum module import capital Enum.
0:40 And then we're going to make a class called color and it's going to subclass enum. And I'm just going to give it a couple attributes
0:48 red is equal to 1, blue is equal to 2 and green is equal to 3. It's all we need to do, very similar to the variables.
0:57 But we're just putting this in the namespace of a class here and by subclassing enum we get some of the benefits of using that.
1:03 Let's run this and see how the test work. Okay, so it looks like I passed that first part and now it's asking me to do some refactoring.
1:15 So let's go down and read the next part. Okay, refactor get_rgb to use the color enumeration. So right now get_rgb is not using color,
1:25 it's using this integer variables that we've defined a pair. So all we need to do is say
1:33 and same thing here and same thing here And presumably whoever's calling get_rgb would pass in or whatnot.
1:54 Just run that and make sure that works. Okay, we are now good with that part.
2:00 Let's go to the next part, create the numeration pet that has dog, cat and fish as the different members, call the enum class to create it.
2:08 So in this case, we're going to call enum rather than subclasses it, it looks similar to the name tuple if you're familiar with that.
2:16 So we would say pet is equal to enum. It says it has a dog, cat and fish. So the first parameter that we give to calling the enum class is
2:36 we give it the name of the class that we're making or the name of the enumeration, very similar to name tuple
2:41 and then we're going to say dog, cat and fish like that. Let's run this and see if it works.
2:51 Okay, so these are two different ways of declaring an enumeration, one is by subclassing enum, the other is by calling it, passing in the name
3:00 and passing in the comma separated list of those values.

Talk Python's Mastodon Michael Kennedy's Mastodon