[Python] 타입어노테이션(type annotation)이란?

Yujeong·2023년 11월 27일
0
post-thumbnail

목차

  1. 타이핑(typing)이 무엇인가?
  2. 타이핑(typing) 방법

1. 타이핑(typing)

python은 동적언어로 런타임 시 변수의 타입(type)이 결정된다.

num1 = 20
print(type(num1))
>>> <class 'int'>

num2 = "이십"
print(type(num2))
>>> <class 'str'>

1) 타이핑(typing)

타입 어노테이션(annotation)으로 (데이터)형에 관한 주석을 붙이는 것이다.

2) 왜 사용하는가?

파이썬 코드의 타입 표시를 표준화함으로써 개발 도중에 예상하지 못한 타입이 들어와 Type Error 발생할 수 있는 경우를 방지할 수 있고, 코드를 좀 더 쉽게 읽을 수 있기 때문에 사용한다.

2. 타이핑(typing) 방법

1) 변수 타입 annotation

다음과 같이 변수명:타입으로 변수를 선언할 수 있다.

name: str = "홍길동"
age: int = 20
emails: list = ["hong@gildong.com", "gildong@hong.com]
devices: dict = {
	"iphone15": "1q2w3e4r",
    "macbookpro": "q1w2e3r4",
    "applewatch": "5t6y7u8i",
    "ipadair5": "t5y6u7i8"
}

2) 함수 타입 annotation

① str

def greeting(name: str) -> str:
    return "Hello " + name

print(greeting("홍길동"))
>>> Hello 홍길동

② int, float

def plus(num1: int=2, num2: float=2.5) -> float:
    return num1 + num2

print(plus())
>>> 4.5
print(type(plus())
>>> <class 'float'>

③ int, str, list

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!']

3) 사용자 정의 타입 annotation

class User:
    ...
    
class Order:
    ...

def get_order(id: int) -> Order:
    ...

def cancel_order(user: User, id: int) -> Order:
    ...

4) 검사

>>> __annotations__
{'emails': list}

참고
https://docs.python.org/ko/3.10/library/typing.html
https://www.daleseo.com/python-type-annotations/

profile
공부 기록

0개의 댓글