4.5. Match Capture

A capture pattern looks like x and is equivalent to an identical assignment target: it always matches and binds the variable with the given (simple) name.

A capture pattern serves as an assignment target for the matched expression. Only a single name is allowed (a dotted name is a constant value pattern). A capture pattern always succeeds.

4.5.1. Problem

>>> color = 'black'
>>>
>>> if color == 'r':
...     print('red')
... elif color == 'g':
...     print('green')
... elif color == 'b':
...     print('blue')
... else:
...     raise ValueError(f'Unknown color: {color}')
...
Traceback (most recent call last):
ValueError: Unknown color: black

4.5.2. Solution

>>> color = 'black'
>>>
>>> match color:
...     case 'r': print('red')
...     case 'g': print('green')
...     case 'b': print('blue')
...     case x: raise ValueError(f'Unknown color: {x}')
...
Traceback (most recent call last):
ValueError: Unknown color: black

4.5.3. Capture vs. Wildcard

  • Underscore _ in match statement is a special syntax

  • In this case, the underscore behaves differently than in assignment expressions

>>> color = 'black'
>>>
>>> match color:
...     case 'r': print('red')
...     case 'g': print('green')
...     case 'b': print('blue')
...     case _: raise ValueError(f'Unknown color: {_}')
...
Traceback (most recent call last):
NameError: name '_' is not defined

4.5.4. Use Case - 1

>>> name = 'Mark'
>>>
>>> match name:
...     case 'Mark':    print('Hello Mark')     # Literal pattern
...     case 'Melissa': print('Hello Melissa')  # Literal pattern
...     case name:      print(f'Hello {name}')  # Capture pattern
...
Hello Mark

4.5.5. Use Case - 2

>>> def myrange(*args, **kwargs):
...     if kwargs:
...         raise TypeError('myrange() takes no keyword arguments')
...
...     match len(args):
...         case 3:
...             start = args[0]
...             stop = args[1]
...             step = args[2]
...         case 2:
...             start = args[0]
...             stop = args[1]
...             step = 1
...         case 1:
...             start = 0
...             stop = args[0]
...             step = 1
...         case 0:
...             raise TypeError('myrange expected at least 1 argument, got 0')
...         case other:
...             raise TypeError(f'myrange expected at most 3 arguments, got {other}')
...
...     current = start
...     result = []
...
...     while current < stop:
...         result.append(current)
...         current += step
...
...     return result

4.5.6. Assignments

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% About
# - Name: Match Capture Range
# - Difficulty: medium
# - Lines: 2
# - Minutes: 2

# %% English
# 1. Write own implementation of a built-in function `range()`
# 2. Note, that function does not take any keyword arguments
# 3. How to implement passing only stop argument
#    `myrange(start=0, stop=???, step=1)`?
# 4. Use literal pattern and capture pattern
# 5. Run doctests - all must succeed

# %% Polish
# 1. Zaimplementuj własne rozwiązanie wbudowanej funkcji `range()`
# 2. Zauważ, że funkcja nie przyjmuje żanych argumentów nazwanych (keyword)
# 3. Jak zaimplementować możliwość podawania tylko końca
#    `myrange(start=0, stop=???, step=1)`?
# 4. Użyj literal pattern i capture pattern
# 5. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - https://github.com/python/cpython/blob/main/Objects/rangeobject.c#LC75
# - `match len(args)`
# - `case count`
# - `raise TypeError('error message')`

# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 10), \
'Python 3.10+ required'

>>> from inspect import isfunction
>>> assert isfunction(myrange)

>>> myrange(0, 10, 2)
[0, 2, 4, 6, 8]

>>> myrange(0, 5)
[0, 1, 2, 3, 4]

>>> myrange(5)
[0, 1, 2, 3, 4]

>>> myrange()
Traceback (most recent call last):
TypeError: myrange expected at least 1 argument, got 0

>>> myrange(1,2,3,4)
Traceback (most recent call last):
TypeError: myrange expected at most 3 arguments, got 4

>>> myrange(stop=2)
Traceback (most recent call last):
TypeError: myrange() takes no keyword arguments

>>> myrange(start=1, stop=2)
Traceback (most recent call last):
TypeError: myrange() takes no keyword arguments

>>> myrange(start=1, stop=2, step=2)
Traceback (most recent call last):
TypeError: myrange() takes no keyword arguments
"""


# myrange(start=0, stop=???, step=1)
# note, function does not take keyword arguments
# type: Callable[[int,int,int], list[int]]
def myrange(*args, **kwargs):
    if kwargs:
        raise TypeError('myrange() takes no keyword arguments')

    match len(args):
        case 3:
            start = args[0]
            stop = args[1]
            step = args[2]
        case 2:
            start = args[0]
            stop = args[1]
            step = 1
        case 1:
            start = 0
            stop = args[0]
            step = 1
        case 0:
            raise TypeError('myrange expected at least 1 argument, got 0')
        case _:
            raise TypeError(f'myrange expected at most 3 arguments, got {len(args)}')

    current = start
    result = []

    while current < stop:
        result.append(current)
        current += step

    return result