HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCritical

Replacements for switch statement in Python?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
pythonswitchforstatementreplacements

Problem

I want to write a function in Python that returns different fixed values based on the value of an input index.

In other languages I would use a switch or case statement, but Python does not appear to have a switch statement. What are the recommended Python solutions in this scenario?

Solution

Python 3.10 (2021) introduced the match-case statement, which provides a first-class implementation of a "switch" for Python. For example:

def f(x):
    match x:
        case 'a':
            return 1
        case 'b':
            return 2
        case _:
            return 0   # 0 is the default case if x is not found


The match-case statement is considerably more powerful than this simple example.

Documentation:

  • match statements (under the "More Control Flow Tools" page)



  • The match statement (under "Compound statements" page)



  • PEP 634 – Structural Pattern Matching: Specification



  • PEP 636 – Structural Pattern Matching: Tutorial



If you need to support Python ≤ 3.9, use a dictionary instead:

def f(x):
    return {
        'a': 1,
        'b': 2,
    }.get(x, 0)  # default case

Code Snippets

def f(x):
    match x:
        case 'a':
            return 1
        case 'b':
            return 2
        case _:
            return 0   # 0 is the default case if x is not found
def f(x):
    return {
        'a': 1,
        'b': 2,
    }.get(x, 0)  # default case

Context

Stack Overflow Q#60208, score: 2244

Revisions (0)

No revisions yet.