[Python] mypy, pyright 설치 및 사용방법
mypy
런타임에서 타입을 체크하는 도구이다. Type hint의 타입을 기반으로 해 오류를 잡아낸다.
▶ mypy 설치
$ pip install mypy
▶ mypy 실행
$ mypy filename.py
▶ mypy실행과 파일 출력 동시에 하기
$ mypy filename.py && python filename.py
▶ 결과
아래와 같은 함수를 예시로 들어 보자.
type hint는 정수로 지정했는데 다른 타입을 넣어 함수를 호출하는 경우이다.
def cal_add(x: int, y: int) -> int:
return x + y
print(cal_add(1, 3))
print(cal_add('hello', 'world'))
print(cal_add([1,2,3], [4,5,6]))
mypy 를 실행시키면,
이렇게 에러가 뜨고 친절하게 어떤 인자가 어떻게 타입을 위반했는지까지 알려준다.
에러가 없다며 이런 성공 메세지가 뜬다.
mypy 체킹과 출력을 동시에 수행하면, 성공메세지와 함께 출력값이 뜬다.
https://mypy.readthedocs.io/en/stable/getting_started.html
Getting started - mypy 0.981 documentation
Previous Home
mypy.readthedocs.io
pyright
다음으로 살펴볼 툴은 pyright이다.
마이크로 소프트가 개발한 타입 체크 도구이며, 속도가 빠르고 안정적인 것으로 알려져 있다. 사용 방법은 mypy와 동일이다.
▶ pyright 설치
$ pip install pyright
▶ pyright 실행
$ pyright filename.py
▶ pyright 실행과 파일 출력
$ pyright filename.py && python filename.py
▶ 결과
mypy에서 사용한 함수와 출력문을 그대로 적용해 보았다.
마찬가지로 에러가 뜨고 에러 이유도 자세히 알려준다.
성공하면 이렇게 결과가 표시된다.
https://github.com/microsoft/pyright
GitHub - microsoft/pyright: Static type checker for Python
Static type checker for Python. Contribute to microsoft/pyright development by creating an account on GitHub.
github.com
※ 주의! mypy와 pyright는 파이썬 공식 언어에서 지원해 주는 타이핑 툴은 아니다. 따라서 필요할 때만 부분적으로 사용하는 것을 권장한다!