[Python] PEP 622 - can match statement be used as an expression?

Discussão em 'Python' iniciado por Stack, Dezembro 1, 2024.

  1. Stack

    Stack Membro Participativo

    PEP 622 introduced match statement as an alternative to if-elif-else. However, one thing I can't find in the proposal or in any of the material online is whether the match statement can be used as an expression and not just as a statement.

    A couple of examples to make it clear:

    Example 1:

    def make_point_2d(pt):
    match pt:
    case (x, y):
    return Point2d(x, y)
    case _:
    raise TypeError("not a point we support")


    Example 2:

    match response.status:
    case 200:
    do_something(response.data)
    case 301 | 302:
    retry(response.location)


    In the first example, the function returns from inside a case clause, and in the second example, nothing is returned. But I want to be able to do something like the following hypothetical example:

    spouse = match name:
    case "John":
    "Jane"
    case "David":
    "Alice"
    print(spouse)


    But it doesn't compile.

    Continue reading...

Compartilhe esta Página