PHpullh

PYTHON · 기초 문법

유니온 타입

Python 3.10+의 | 연산자로 여러 타입을 허용하는 유니온 타입을 간결하게 표현합니다.

기초 문법중급Union유니온Optional타입파이프

핵심 설명

Python 3.10+의 | 연산자로 여러 타입을 허용하는 유니온 타입을 간결하게 표현합니다.

Python code

# Python 3.10+ 파이프 문법
def process(value: int | str) -> str:
    if isinstance(value, int):
        return f"숫자: {value * 2}"
    return f"문자: {value.upper()}"

print(process(5))        # 숫자: 10
print(process("hello"))  # 문자: HELLO

# Optional은 X | None 의 단축
def find_user(user_id: int) -> str | None:
    users = {1: "Alice", 2: "Bob"}
    return users.get(user_id)

result = find_user(1)
if result is not None:
    print(result.upper())  # ALICE

# isinstance에서도 사용 (3.10+)
def check(val: object) -> str:
    if isinstance(val, int | str):
        return f"int 또는 str: {val}"
    return "기타 타입"

print(check(42))       # int 또는 str: 42
print(check([1, 2]))   # 기타 타입

학습 팁

X | NoneOptional[X]와 동일하지만 더 직관적입니다. Python 3.10+에서는 파이프 문법을 권장합니다.

주의할 점

Python 3.9 이하에서는 int | str 문법을 사용할 수 없습니다. Union[int, str]을 사용하세요.

자주 묻는 질문

유니온 타입란 무엇인가요?

Python 3.10+의 | 연산자로 여러 타입을 허용하는 유니온 타입을 간결하게 표현합니다.

유니온 타입 학습 시 주의할 점은 무엇인가요?

Python 3.9 이하에서는 int | str 문법을 사용할 수 없습니다. Union[int, str] 을 사용하세요.

Continue Learning

Python 학습을 이어가세요

총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.