python은 동적언어로 런타임 시 변수의 타입(type)이 결정된다.
num1 = 20
print(type(num1))
>>> <class 'int'>
num2 = "이십"
print(type(num2))
>>> <class 'str'>
타입 어노테이션(annotation)으로 (데이터)형에 관한 주석을 붙이는 것이다.
파이썬 코드의 타입 표시를 표준화함으로써 개발 도중에 예상하지 못한 타입이 들어와 Type Error 발생할 수 있는 경우를 방지할 수 있고, 코드를 좀 더 쉽게 읽을 수 있기 때문에 사용한다.
다음과 같이 변수명:타입
으로 변수를 선언할 수 있다.
name: str = "홍길동"
age: int = 20
emails: list = ["hong@gildong.com", "gildong@hong.com]
devices: dict = {
"iphone15": "1q2w3e4r",
"macbookpro": "q1w2e3r4",
"applewatch": "5t6y7u8i",
"ipadair5": "t5y6u7i8"
}
def greeting(name: str) -> str:
return "Hello " + name
print(greeting("홍길동"))
>>> Hello 홍길동
def plus(num1: int=2, num2: float=2.5) -> float:
return num1 + num2
print(plus())
>>> 4.5
print(type(plus())
>>> <class 'float'>
def get_emails(emails: list) -> str:
return ' '.join(emails)
print(get_emails())
>>> hong@gildong.com gildong@hong.com
def repeat(message: str, times: int = 3) -> list:
return [message] * times
print(repeat("studying!"))
>>> ['studying!', 'studying!', 'studying!']
class User:
...
class Order:
...
def get_order(id: int) -> Order:
...
def cancel_order(user: User, id: int) -> Order:
...
>>> __annotations__
{'emails': list}
참고
https://docs.python.org/ko/3.10/library/typing.html
https://www.daleseo.com/python-type-annotations/