파이썬/타입 힌트

Python 타입힌트: Union 타입 활용법

Data Jun 2025. 9. 10. 15:22

Python의 타입힌트(Type Hint)는 하나의 변수나 함수 인자가 여러 가지 타입을 가질 수 있을 때도 대응할 수 있습니다.
이때 사용하는 것이 바로 Union 타입입니다.

Union은 “이 값은 A 타입일 수도 있고, B 타입일 수도 있다”라는 의미를 나타내며, 코드의 유연성과 안정성을 동시에 확보할 수 있습니다.

 

기본 사용법

Union은 typing 모듈에서 제공되며, 다음과 같이 사용할 수 있습니다

from typing import Union

def to_str(value: Union[int, float]) -> str:
    return str(value)

print(to_str(10))     # "10"
print(to_str(3.14))   # "3.14"

위 코드에서 value는 int 또는 float 타입일 수 있으며, 둘 다 허용됩니다.

 

다양한 타입 조합

Union은 두 개 이상의 타입을 동시에 지정할 수도 있습니다.

from typing import Union

def stringify(data: Union[int, float, str]) -> str:
    return f"value={data}"

print(stringify(100))       # "value=100"
print(stringify(3.14))      # "value=3.14"
print(stringify("hello"))   # "value=hello"

여기서 data는 int, float, str 중 하나일 수 있습니다.

 

반환 타입에 활용하기

함수의 반환값이 여러 가지 타입일 수도 있습니다.

from typing import Union

def parse_number(text: str) -> Union[int, float]:
    if "." in text:
        return float(text)
    return int(text)

print(parse_number("42"))    # int
print(parse_number("3.14"))  # float

IDE나 타입체커는 반환값이 int 또는 float가 될 수 있음을 인식합니다.

 

Python 3.10 이후 개선된 문법 (| 연산자)

Python 3.10부터는 Union을 더 간결하게 쓸 수 있도록 | 연산자 문법이 추가되었습니다.

def to_str(value: int | float) -> str:
    return str(value)

print(to_str(100))
print(to_str(3.14))

즉, Union[int, float] 대신 int | float를 사용할 수 있습니다. 이 방식은 가독성이 좋고 최신 Python 코드에서 권장됩니다.

 

정리

  • Union 은 여러 타입을 동시에 허용할 때 사용
  • Union[str, None]은 Optional[str]으로 줄여 쓸 수 있음
  • 반환 타입이 여러 경우일 때도 활용 가능
  • Python 3.10부터는 Union[int, float] 대신 int | float 형태를 권장

Union 타입을 사용하면 함수와 변수의 타입을 더 유연하게 정의할 수 있으며, IDE 자동완성과 타입체커 지원을 통해 안정적인 코드 작성을 도울 수 있습니다.