serhii.net

In the middle of the desert you can say anything you want

05 May 2023

Python 3.10 has a case statement

4. More Control Flow Tools — Python 3.10.11 documentation:

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the internet"

Also

case 401 | 403 | 404:
    return "Not allowed"

and

match points:
    case []:
        print("No points")
    case [Point(0, 0)]:
        print("The origin")
    case [Point(x, y)]:
        print(f"Single point {x}, {y}")
    case [Point(0, y1), Point(0, y2)]:
        print(f"Two on the Y axis at {y1}, {y2}")
    case _:
        print("Something else")

Lastly, you can capture subpatterns:

case (Point(x1, y1), Point(x2, y2) as p2): ...

Generally - #todo - I should systematically read up on new things in the not-latest-anymore Python versions, e.g.:

Nel mezzo del deserto posso dire tutto quello che voglio.
comments powered by Disqus