Chapter 091 / 132 · Level 6 · Advanced Python & concurrency

Modern pattern matching

Complete Python PDF
Checking PDF availability…

Chapter 91 of 132 · Level 6 · Advanced Python & concurrency · Python demonstrations with recorded outputs. Learn through reading, predicting and testing real Python code.

Code + real outputPractice + explanationsOffline Python exercises
Course disclaimer · independent educational content
EasyTutorGuide creates independent educational tutorials. Python and other product names remain the property of their owners; this course is not endorsed by the Python Software Foundation or third-party providers. Examples are for learning and should be reviewed and tested before production use. Do not expose real API keys or private data. Translation is automated and may introduce errors; code examples remain untranslated. Terms · Privacy · Legal.
01 · Why this concept matters

Structural pattern matching checks the shape of data rather than only its equality. Mapping patterns and sequence patterns can make complex message handlers readable, but explicit if branches are simpler for small cases.

Learning goal: Modern pattern matching. Start by reading what the program does, then inspect its exact output. Where an example illustrates only a prerequisite, study the named advanced feature separately before using it in production.

02 · The important subtopics

Study these connected ideas as you work through the demonstration:

  • match guards and destructuring
  • Sequence and mapping patterns
  • Class patterns
  • When matching is worse than if/elif
03 · Pinpoint: read the code line by line
  1. Line 1def classify(value):Define or import. Notice what values enter this statement and which names it affects.
  2. Line 2match value:Create, update, or use a value. Notice what values enter this statement and which names it affects.
  3. Line 3case {'status': 'ok', 'count': count}:Create, update, or use a value. Notice what values enter this statement and which names it affects.
  4. Line 4return f'accepted {count}'Control the next step. Notice what values enter this statement and which names it affects.
  5. Line 5case ['error', message]:Create, update, or use a value. Notice what values enter this statement and which names it affects.
  6. Line 6return f'problem: {message}'Control the next step. Notice what values enter this statement and which names it affects.
  7. Line 7case _:Create, update, or use a value. Notice what values enter this statement and which names it affects.
  8. Continue through the remaining lines in order; use the displayed output to check your interpretation.
Input → operation → output

Find the literal input values and arguments, follow each operation in execution order, and verify the result below. This habit turns a code listing into a testable explanation.

04 · Runnable Python example and verified output

Modern pattern matching: working demonstration

Python · runnable
PYTHON CODE
def classify(value):
    match value:
        case {'status': 'ok', 'count': count}:
            return f'accepted {count}'
        case ['error', message]:
            return f'problem: {message}'
        case _:
            return 'unknown'
print(classify({'status': 'ok', 'count': 3}))
Verified execution ▼
accepted 3

Why it works: Structural pattern matching checks the shape of data rather than only its equality. Mapping patterns and sequence patterns can make complex message handlers readable, but explicit if branches are simpler for small cases.

Worked example 2 · Modern Pattern Matching in practice

Python · executed and checked
PYTHON CODE
status = 404
match status:
    case 200: message = 'ok'
    case 404: message = 'not found'
    case _: message = 'other'
print(message)
Verified execution output
not found

Pinpoint learning: This practical modern pattern matching demonstration uses a small input you can inspect. Run it exactly as shown, compare the displayed result, then change one value and predict how the result will change.

Understand the code line by line
  1. 1: status = 404 — Store or update the value on the left using the expression on the right.
  2. 2: match status: — Execute this statement and observe its effect on later values.
  3. 3: case 200: message = 'ok' — Store or update the value on the left using the expression on the right.
  4. 4: case 404: message = 'not found' — Store or update the value on the left using the expression on the right.
  5. 5: case _: message = 'other' — Store or update the value on the left using the expression on the right.
  6. 6: print(message) — Display the value so you can compare it with the verified output.

Worked example 3 · Change one input and compare

Python · executed and checked
PYTHON CODE
status = 406
match status:
    case 200:
        message = 'ok'
    case 404:
        message = 'not found'
    case _:
        message = 'other'
print(message)
Verified execution output
other

Pinpoint learning: Exactly one literal input was changed from the preceding demonstration. Compare the outputs: identify the modified value, trace the operation, and explain which result changed. The displayed output was produced by executing this variant.

Understand the code line by line
  1. 1: status = 406 — Store or update the value on the left using the expression on the right.
  2. 2: match status: — Execute this statement and observe its effect on later values.
  3. 3: case 200: — Execute this statement and observe its effect on later values.
  4. 4: message = 'ok' — Store or update the value on the left using the expression on the right.
  5. 5: case 404: — Execute this statement and observe its effect on later values.
  6. 6: message = 'not found' — Store or update the value on the left using the expression on the right.
  7. 7: case _: — Execute this statement and observe its effect on later values.
  8. 8: message = 'other' — Store or update the value on the left using the expression on the right.
  9. 9: print(message) — Display the value so you can compare it with the verified output.
05 · Independent practice and answer guidance

Exercise A · Adapt the code

Add a case that handles a message with a warning code.

Exercise B · Predict

Before pressing Run, predict the first displayed line. Next, change one literal value and record the new observed output. Explain the difference in one clear sentence.

Exercise C · Debug

Make a temporary invalid change, read the exception or failed assertion if one occurs, restore the working code, and explain the repair.

Worked explanation for the original example

Structural pattern matching checks the shape of data rather than only its equality. Mapping patterns and sequence patterns can make complex message handlers readable, but explicit if branches are simpler for small cases.

accepted 3
06 · Build, verify and advance

Real-world task: Parse a small command language with structural patterns.

Mastery checklist

Run the original code; explain the important lines; change one input and verify the new outcome; use a test or recorded result to justify your conclusion.