Using Basic Patterns: OR, Capture, and Guards
00:00 Let’s explore a few more fundamental pattern types. In this lesson, you’ll see OR patterns, capture patterns, and guards.
00:08 First up, OR patterns. OR patterns use the bitwise OR operator. Some call it a vertical bar, some call it a pipe. They’re used to combine structural patterns into a union of alternative subpatterns.
00:22
For example, match subject: case "python"
| 42: print("It's Python
or 42")
. “Python” or 42 will match the case
clause.
00:35
Moving on to capture patterns, these are as interesting as they are powerful. Capture patterns are like defining a variable inside your case
clause. Capture patterns create local variables that can be used within the case
block.
00:48
They must, however, use valid variable names in Python, just like any other variable declaration. For example, match subject: case what_it_is:
print(f"{what_it_is}")
.
01:01
So what_it_is
in this case captures the content of subject
, making it usable in the corresponding code block.
01:11 But be careful because when used without a guard, this matches to any subject unconditionally, probably not what you want to do.
01:19
Speaking of guards, you can build even more complex case
clauses by using guards. Guards add conditional logic to the case
clause.
01:27
They’re part of the case
clause and not part of the structural pattern itself. In fact, guards will only be evaluated when the related pattern matches the subject.
01:38
Here’s an example: match subject: case what_it_is
if what_it_is == "python":
print("It's Python")
.
01:48
what_it_is
captures the subject, but the code block only executes when what_it_is
is equal to the string “python”. The if
condition is the guard.
01:58 I’ll admit these examples are simple and a little silly, but now you’re ready to open up your IDE and get started on using these patterns to improve your REPL.
Become a Member to join the conversation.