컴퓨터/파이썬

Python 3.10 미리보기 (switch case)

두뇌미포함 2021. 1. 11. 19:55
728x90
반응형

Structural Pattern Matching

 

PEP 622 -- Structural Pattern Matching

The official home of the Python Programming Language

www.python.org

 

1. 소개

3.10 버전에 추가될 match, case 문법을 미리 보면 다음과 같다.

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 401:
            return "Unauthorized"
        case 403:
            return "Forbidden"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something else"

 

자바의 switch문과 같은 기능이 추가될 것으로 보인다.

Scala, Erlang과 비슷하게 작동할 것이며, 이미 있는 시퀀스 unpacking 문법을 이용했다고 한다. (a, b = value)

 

기존 문법

def is_tuple(node):
    if isinstance(node, Node) and node.children == [LParen(), RParen()]:
        return True
    return (isinstance(node, Node)
            and len(node.children) == 3
            and isinstance(node.children[0], Leaf)
            and isinstance(node.children[1], Node)
            and isinstance(node.children[2], Leaf)
            and node.children[0].value == "("
            and node.children[2].value == ")")

match를 이용한 문법

def is_tuple(node: Node) -> bool:
    match node:
        case Node(children=[LParen(), RParen()]):
            return True
        case Node(children=[Leaf(value="("), Node(), Leaf(value=")")]):
            return True
        case _:
            return False

 

참고

PEP 622 @링크

 

PEP 622 -- Structural Pattern Matching

The official home of the Python Programming Language

www.python.org

CPython @Github 링크

위 python을 컴파일해서 사용하면 미리 체험해 볼 수 있다.

728x90