본문 바로가기
Modern Python Cookbook 정리

[Python] type hint

by 자동매매 2022. 10. 24.

1. 내장함수 type 이용

>>> a_string_variable = "Hello, world!"
>>> type(a_string_variable)
<class 'str'>
>>> a_string_variable = 42
>>> type(a_string_variable)
<class 'int'>

 

2. mypy 패키지 사용( Third-partylibraries )

1) 설치 ( 명령 프롬프트 이용 )

    - 기본 방법                   : python -m pip install mypy 

    - conda tool 이용 방법 : conda install mypy 

    # anaconda등을 설치하면 프로그램 목록에서 명령프롬프트가 동시에 설치 됨을 확인할 수 있다.

 

2) 파일 준비

    - 파일 저장 위치 : C:\Users\User01\source\repos\oop_test\main.py

# main.py
def odd(n: int) -> bool:
    return n % 2 != 0

def main():
    print(odd("Hello, world!"))   # odd의 인자 전달 error발생

if  name  == " main ":
    main()

 

3) type 확인 ( 명령 프롬프트 이용)

    mypy --strict 파일경로

% mypy --strict  C:\Users\User01\source\repos\oop_test\main.py

 

[ 실행 결과 ]

Success: no issues found in 1 source file

C:\WINDOWS\system32>mypy --strict C:\Users\neo21\source\repos\oop_test\main.py
C:\Users\neo21\source\repos\oop_test\main.py:4: error: Function is missing a return type annotation
C:\Users\neo21\source\repos\oop_test\main.py:4: note: Use "-> None" if function does not return a value
C:\Users\neo21\source\repos\oop_test\main.py:5: error: Argument 1 to "odd" has incompatible type "str"; expected "int"
C:\Users\neo21\source\repos\oop_test\main.py:7: error: Name 'name' is not defined
C:\Users\neo21\source\repos\oop_test\main.py:8: error: Call to untyped function "main" in typed context
Found 4 errors in 1 file (checked 1 source file)

 

댓글