python_syntax_match

nowhere·2022년 1월 19일
0

Match

  • 조건문으로 여러 상황에 대한 분기처리를 해주다가 우연히 발견했다.
  • Python3.10 부터 사용 가능하다.
  • 파이썬 공식문서에서의 match keyword(statements)에 대한 설명은 다음과 같다.

A match statement takes an expression and compares its value to successive patterns given as one or more case blocks. This is superficially similar to a switch statement in C, Java or JavaScript (and many other languages), but it can also extract components (sequence elements or object attributes) from the value into variables.

자바스크립트와 자바를 사용했던 경험이 있던 차에 이런 기능은 정말 반갑고 고마웠다.

그리고 파이썬스러운 작동까지 가능하다니 기능이 상당히 확장된 느낌이다.

class TEST:
    x:int
    y:int
    
    def __init__(self,x:int,y:int):
        self.x = x
        self.y = y
    
t = TEST(1,2)
match t:
    case TEST(x=0,y=0):
        print('(0,0)')
    case TEST(x=0,y=y):
        print('(0,{})'.format(y))
    case TEST(x=x,y=0):
        print('({},y)'.format(x))
    case TEST(x=x,y=y):
        print('({},{})'.format(x,y))
        
t = TEST(1,1)
match t:
    case TEST(x=x, y=y) if x == y:
        print(f"Y=X at {x}")
    case TEST(x=x, y=y):
        print(f"Not on the diagonal")

ts = [TEST(1,1),t]
match ts:
    case [TEST(x=x1,y=y1),TEST(x=x2,y=y2)]:
        print('there is two objects')
    case _: # no case matched then,
        print('no one..')

유의사항

  • arguments의 경우 key arguments로 넣어주자.
  • 파이썬의 객체지향적인 특징(모든 것이 객체다.)은 match와 굉장히 잘 어울린다.

참고

https://docs.python.org/3/tutorial/controlflow.html#match-statements

profile
수익성은 없으니 뭐라도 적어보는 벨로그

0개의 댓글