Using Enumerations in if and match Statements
00:00
Using enumerations in if
and match
statements. Chained if
/elif
statements and the match
/case
statement introduced in Python 3.10 are common and arguably natural places where you can use enumerations.
00:15 Both constructs allow you to take different courses of action depending on certain conditions. Let’s say you have a piece of code that handles a semaphore or a traffic light in a traffic control application.
00:29 You must perform different actions depending on the current light of the semaphore. In this situation, you can use an enumeration to represent the semaphore and its lights.
00:39
Then you can use a chain of if
/elif
statements to decide on the action to run
00:53
the chain of statements in. The handle_semaphore()
function checks the value of the current light to decide on the action to take. Note that the calls to print()
in handle_semaphore()
are just placeholders. In real code, you’d replace them with more complex operations.
01:35
In Python 3.10 or later, you can turn these statements into an equivalent match
/case
statement.
01:59
This new implementation of handle_semaphore()
is equivalent to the previous implementation that uses if
/elif
statements.
02:06
Using either technique is a matter of taste and style. Both work well and are comparable in terms of readability. But note, if you need to guarantee backward compatibility with Python versions lower than 3.10, then you must use chained if
/elif
statements.
02:30
A final note is that even though enumerations seem to play well with if
/elif
and match
/case
statements, you must keep in mind that these don’t scale well.
02:40 If you add new members to your target enumeration, then you’ll need to update the handling function to consider these new members.
02:49 In the next section of the course, you’ll see how to compare and sort enumerations.
Become a Member to join the conversation.