개발/Python
[Python] 파이썬 버전에 따른 타입힌트/어노테이션 사용
nyukist
2023. 4. 7. 23:37
파이썬 버전에 따라서 타입힌트를 typing 모듈로 해야할 지 파이썬 내장함수로 해야할 지 결정이 되는 것 같다.
(왜냐하면.. 여러 환경에서 개발을 하다보니 에러를 겪었기 때문에)
1. 타입 힌트는 파이썬3.5 부터 지원한다.
1 - 1. typing의 타입들을 사용한 예
from typing import List, Dict, Tuple
ko_currencies: List = [100, 500, 1000, 5000, 10000]
count_has_money: Dict = {
"hundred-won": 0,
"five-hundred-won": 1,
"thousand-won": 0,
"five-thousand-won": 2,
"ten-thousand-won": 5,
}
my_money: Tuple[List, Dict] = ko_currencies, count_has_money
def money(a: int, b: List) -> Tuple:
return c, d
파이썬3.5 부터 파이썬3.9 미만의 버전을 사용한다면 위 예처럼 typing 모듈을 사용하여 작성해야한다.
2. 파이썬3.9 부터는 파이썬 기본함수(built-in functions)를 타입 힌트로 사용할 수 있다.
만약 작성하신 코드가 파이썬 3.9 보다 낮은 버전의 환경에서 쓰일 수 있다면 typing 모듈로 쓰는 것이 낫다.
(요새 거의 모든 파이썬 개발환경을 3.9 이상을 쓰긴하지만 레거시가 깊은 곳에는 그 이하 버전을 쓰는 경우가 있을 수도)
2 - 1. typing 없이 타입 힌트를 사용한 예
ko_currencies: list = [100, 500, 1000, 5000, 10000]
count_has_money: dict = {
"hundred-won": 0,
"five-hundred-won": 1,
"thousand-won": 0,
"five-thousand-won": 2,
"ten-thousand-won": 5,
}
my_money: tuple[list, dict] = ko_currencies, count_has_money
def money(a: int, b: list) -> tuple:
return c, d
그러면 파이썬 3.9 이상이라면 typing 을 굳이 쓸 필요가 없을까?
그건 아니다.
list, dict, set (컨테이너형 타입들) 이나 int, str 타입 등등 과 함께 단순하게 작업한다면 typing 모듈없이 사용할 수 있지만,
typing 에는 매우 편리하고 좋은 기능들이 있기 때문에 필요에 따라서 typing 을 같이 쓰는게 더 좋다.
2 - 2. typing 과 파이썬 내장함수를 같이 활용한 예
import datetime
from typing import Union, Optional
def korean_dow(dt: Union[datetime.date, datetime.datetime]):
return '월화수목금토일'[dt.isoweekday() - 1]
def make_text_with_(
text: str,
is_result: Optional[bool] = False,
input_language: Optional[str] = None,
filters: Optional[dict] = None,
) -> None:
return None