4.4. Match Wildcard

The wildcard pattern is a single underscore: _. It always matches, but does not capture any variable (which prevents interference with other uses for _ and allows for some optimizations).

4.4.1. Problem

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

4.4.2. Solution

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

4.4.3. Use Case - 1

>>> user = 'Mark'
>>>
>>> match user:
...     case 'Mark':        print('Hello Mark')
...     case 'Melissa':     print('Hello Melissa')
...     case 'Rick':        print('Hello Rick')
...     case 'Alex':        print('Hello Alex')
...     case 'Beth':        print('Hello Beth')
...     case 'Chris':       print('Hello Chris')
...     case _:             raise PermissionError
...
Hello Mark

4.4.4. Use Case - 2

>>> def html_color(name):
...     match name:
...         case 'red':   return '#ff0000'
...         case 'green': return '#00ff00'
...         case 'blue':  return '#0000ff'
...         case _:       raise NotImplementedError('Unknown color')
>>> html_color('black')
Traceback (most recent call last):
NotImplementedError: Unknown color
>>> html_color('orange')
Traceback (most recent call last):
NotImplementedError: Unknown color

4.4.5. Use Case - 3

>>> weekday = 0
>>>
>>> match weekday:
...     case 1: print('Monday')
...     case 2: print('Tuesday')
...     case 3: print('Wednesday')
...     case 4: print('Thursday')
...     case 5: print('Friday')
...     case 6: print('Saturday')
...     case 7: print('Sunday')
...     case _: raise ValueError('Invalid weekday')  # wildcard pattern
...
Traceback (most recent call last):
ValueError: Invalid weekday

4.4.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 Wildcard Range
# - Difficulty: medium
# - Lines: 18
# - Minutes: 5

# %% 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 wildcard 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 wildcard pattern
# 5. Uruchom doctesty - wszystkie muszą się powieść

# %% Hints
# - https://github.com/python/cpython/blob/main/Objects/rangeobject.c#LC75
# - `match len(args)`
# - `case _`
# - `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')

    if len(args) == 3:
        start = args[0]
        stop = args[1]
        step = args[2]
    elif len(args) == 2:
        start = args[0]
        stop = args[1]
        step = 1
    elif len(args) == 1:
        start = 0
        stop = args[0]
        step = 1
    elif len(args) == 0:
        raise TypeError('myrange expected at least 1 argument, got 0')
    else:
        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