파이썬 3.13 패턴 매칭 및 핵심 기능 심화 분석

패턴 매칭 구문

파이썬의 match 문은 구조화된 데이터 처리에 효율적입니다.

기본 패턴 매칭

def handle_http_code(code):
    match code:
        case 400:
            return "잘못된 요청"
        case 404:
            return "찾을 수 없음"
        case 418:
            return "나는 찻주전자"
        case _:
            return "알 수 없는 오류"

복합 패턴 처리

# 좌표 처리
def locate(position):
    match position:
        case (0, 0):
            print("원점")
        case (0, y_val):
            print(f"Y축: {y_val}")
        case (x_val, 0):
            print(f"X축: {x_val}")
        case (x_val, y_val):
            print(f"좌표: ({x_val}, {y_val})")
        case _:
            raise ValueError("유효하지 않은 좌표")

# 클래스 매칭
class Vertex:
    __match_args__ = ('pos_x', 'pos_y')
    def __init__(self, pos_x, pos_y):
        self.pos_x = pos_x
        self.pos_y = pos_y

def detect_vertex(v):
    match v:
        case Vertex(0, 0):
            print("원점 버텍스")
        case Vertex(0, y) if y > 0:
            print(f"상단 Y축: {y}")
        case Vertex(x, 0) as pt:
            print(f"X축 버텍스: {pt}")

클래스 메서드 유형

class Processor:
    @classmethod
    def process_class(cls, param):
        print(f"{cls.__name__} 처리: {param}")

    @staticmethod
    def process_static(param1, param2):
        return param1 + param2

숫자 표현 개선

large_number = 12_345_678
scientific_val = 1.602e-19

할당 표현식 연산자

data_stream = [7, 8, 9, 10]
if (item_count := len(data_stream)) > 3:
    print(f"항목 수 {item_count}개, 기준 초과")

포맷 문자열 기능

user_id = "dev_user"
access_count = 42
print(f"사용자 {user_id!r} 접속: {access_count:04d}회")

# 출력: 사용자 'dev_user' 접속: 0042회

타입 어노테이션 활용

from collections.abc import Sequence

def calculate_total(items: Sequence[float]) -> float:
    return sum(items)

coordinates: tuple[int, ...] = (10, 20)
matrix: list[list[float]] = [[1.1, 2.2], [3.3, 4.4]]

객체 변경 가능성

# 불변 객체
text = "Python"
try:
    text[0] = "J"
except TypeError:
    print("문자열은 불변 객체")

# 가변 객체
version_history = [3.9, 3.10]
version_history.append(3.11)
print(f"버전 기록: {version_history}")

객체 비교 연산

first_list = [1, 2, 3]
second_list = [1, 2, 3]
list_ref = first_list

print(first_list == second_list)  # 값 비교: True
print(first_list is second_list)  # 참조 비교: False
print(first_list is list_ref)     # 참조 동일: True

태그: Python3.13 pattern-matching Type-Hinting f-string Walrus-Operator

7월 4일 23:29에 게시됨