[Python] type annotation (type hint)

2022. 2. 27. 15:46· Language/Python

타입 어노테이션(type annotation) 또는 타입 힌트(type hint)가 점점 많은 파이썬 프로젝트에서 사용되고 있는 추세
파이썬 버전 3.5에 추가

Type Annotation

def greet(greeting: str, name: str) -> str:
    return greeting + name

greet 라는 함수의 파라미터 greeting, name 이 문자열 이라는 것을 알 수 있고, 리턴 값이 문자열이라는것을 알 수 있다.

 

그러면 만약에..

print(greet(1, 2))

(venv) limjian@Jians-MacBook-Pro-13 python % python3 type_annotation.py 
3

greet 라는 함수에 파라미터를 정수를 넣었을 때.. 그래도 잘 출력 되는 것을 볼 수 있다.

이렇게 type annotation, type hint 는 주석일 뿐.. 부정확하다고 해서 경고나 오류가 발생하는것이 아니다.

 

만약에 실행했을 때 타입을 체크하고싶으면

https://pypi.org/project/mypy/

 

mypy

Optional static typing for Python

pypi.org

mypy 라는 모듈을 사용하면 된다.

(venv) limjian@Jians-MacBook-Pro-13 python % pip install mypy

(venv) limjian@Jians-MacBook-Pro-13 python % mypy type_annotation.py

type_annotation.py:5: error: Argument 1 to "greet" has incompatible type "int"; expected "str"
type_annotation.py:5: error: Argument 2 to "greet" has incompatible type "int"; expected "str"
Found 2 errors in 1 file (checked 1 source file)

 

List, Tuple, Dict, Set

typing 모듈에서 제공하는 List, Tuple, Dict, Set 을 사용하여 annotation, hint 를 추가하면 된다.

from typing import List

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]: 
        ...

        ...
 
    	return


"""
import 를 하지 않고 실행하면

def twoSum(self, nums: List[int], target: int) -> List[int]:
IndentationError: expected an indented block after function definition on line 9

이런 오류가 발생함
"""

 

NewType

type을 새로 정의해서 사용 할 수 있다.

UserId = NewType('UserId', int)
some_id = UserId(524313)



def get_user_name(user_id: UserId) -> str:
    
    return ""
    

# typechecks
user_a = get_user_name(UserId(42351))

# does not typecheck; an int is not a UserId
user_b = get_user_name(-1)

"""

type_annotation.py:15: error: Argument 1 to "get_user_name" has incompatible type "int"; expected "UserId"

"""

user_b 를 실행했을 때, mypy 로 실행시키면 UserId 라는 타입을 기대한다는 오류 메시지를 볼 수 있다.

 

 

Type aliases

alias 를 사용하여 type 을 정의 할수 있다.

Vector = list[float]


def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]


# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])

 

복잡한 타입을 alias 사용

from collections.abc import Sequence

ConnectionOptions = dict[str, str]
Address = tuple[str, int]
Server = tuple[Address, ConnectionOptions]

def broadcast_message(message: str, servers: Sequence[Server]) -> None:
    ...

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
        message: str,
        servers: Sequence[tuple[tuple[str, int], dict[str, str]]]) -> None:
    ...

 

참고

python doc typing

'Language > Python' 카테고리의 다른 글

[Python] ubuntu16.04 python3.8 (e: unable to locate package python3.8)  (0) 2024.04.16
[Python] type  (0) 2022.07.01
[Python] pip requirements.txt  (0) 2022.01.31
[Python] AES 암호/복호화  (2) 2022.01.31
[Python] Object type <class 'str'> cannot be passed to C code (AES)  (0) 2022.01.31
'Language/Python' 카테고리의 다른 글
  • [Python] ubuntu16.04 python3.8 (e: unable to locate package python3.8)
  • [Python] type
  • [Python] pip requirements.txt
  • [Python] AES 암호/복호화
임쟌
임쟌
임쟌
Jian's Blog
임쟌
전체
오늘
어제

공지사항

  • [자기소개]
  • 쟌's Blog (227)
    • Language (32)
      • Python (8)
      • Go (24)
      • Java (0)
    • Framework (10)
      • Django (9)
      • Gin (1)
      • Spring boot (0)
      • Fiber (0)
    • Database (10)
      • PostgreSQL (8)
      • MySQL (0)
      • Redis (2)
    • Server (51)
      • Linux (16)
      • Git (12)
      • Oracle Cloud Infrastructure (13)
      • Mac (4)
      • Docker (4)
      • RabbitMQ (0)
      • ETC (2)
    • Operating System (0)
      • OS (0)
    • Algorithm (22)
      • Go (22)
      • Python (0)
    • Exam Certification (4)
    • Daily Life (27)
      • Review (21)
      • Diary (6)
    • 이공계전문기술연수 (71)
      • Java (17)
      • Database (8)
      • HTML | CSS (13)
      • JavaScript | jQuery (6)
      • Servlet | JSP (16)
      • Spring Framework (11)

인기 글

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.2
임쟌
[Python] type annotation (type hint)
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.