Backend2024년 10월 3일1분 읽기

Python 타입 힌트 심화 — Protocol, TypeGuard, Annotated

YS
YoungSam
조회 1957

Protocol 클래스

구조적 서브타이핑(structural subtyping)을 지원합니다. 명시적 상속 없이 인터페이스를 만족하면 됩니다.

from typing import Protocol

class Drawable(Protocol):
    def draw(self) -> None: ...

class Circle:
    def draw(self) -> None:
        print("Drawing circle")

def render(shape: Drawable) -> None:
    shape.draw()

render(Circle())  # OK — draw() 메서드 존재

TypeGuard

from typing import TypeGuard

def is_str_list(val: list) -> TypeGuard[list[str]]:
    return all(isinstance(x, str) for x in val)
PythonType HintsMyPy

댓글 0

아직 댓글이 없습니다.