Mypy

Mypy는 Python 코드에 대해 정적 타입 검사를 수행하는 도구입니다.

이는 TypeScript의 컴파일러와 유사한 역할을 수행하며, 코드에서 타입 오류를 찾아내는 데 도움이 됩니다​.

 

예제:
먼저 mypy를 설치합니다:

pip install mypy


다음은 mypy를 사용한 Python 코드 예제입니다:(name에 대해 str이라는 어노테이션을 했음에 주목. python 3.5기능)

# 파일명: example.py

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

age: int = "25"  # 이 줄은 타입 오류를 발생시킵니다.

print(greeting("Alice"))


터미널에서 mypy를 사용하여 코드를 검사합니다:

mypy example.py

이 명령을 실행하면, mypy는 age: int = "25"라인에서 타입 오류를 발견하고 이를 알려줍니다.

 


Pytype:

Pytype은 또 다른 Python 정적 타입 검사 도구.

어노테이션이 없어도 추론을 기반으로 동작함.

 

예를들어 아래와 같이 어노테이션이 없는 코드에 대해서 pytype을 수행하면

def multiply_numbers(a, b):
    return a * b

result = multiply_numbers(5, '3')
print(result)

아래처럼 런타임전 경고를 확인할 수 있음(런타임에서는  Python은 문자열 '3'을 5번 반복하여 '33333'을 생성하고 오류로 판단하지 않음)

$ pytype example.py
Computing dependencies
Analyzing 1 sources with 0 local dependencies
ninja: Entering directory `/Users/user/.pytype'
[1/1] check example
FAILED: /Users/user/.pytype/pyi/example.pyi 
pytype-single --imports_info /Users/user/.pytype/imports/example.imports --module-name example -V 3.8 -o /Users/user/.pytype/pyi/example.pyi --analyze-annotated --nofail --quick /Users/user/example.py
File "/Users/user/example.py", line 4, in <module>: unsupported operand type(s) for *: 'int' and 'str' [unsupported-operands]
  Function multiply_numbers was called with the wrong arguments (1:15)

For more details, see https://google.github.io/pytype/errors.html#unsupported-operands.
ninja: build stopped: subcommand failed.

 

Mypy vs Pytype

Mypy

Mypy는 Dropbox에서 개발되었으며, Python의 첫 번째 정적 타입 검사 시스템으로 간주됩니다.

이 도구는 2012년부터 개발이 시작되었으며, 아직도 활발하게 개발이 진행되고 있습니다​.
Mypy는 standalone으로 실행되거나, 커맨드 라인이나 편집기 또는 IDE의 linter 통합의 일부로 작동할 수 있습니다.
Mypy는 타입 어노테이션을 포함하지 않은 코드에 대해 대부분의 코드 검사를 수행하지 않으며, 이는 점진적으로 코드 기반을 주석 처리하고 있는 경우 Mypy가 시간을 낭비하지 않도록 하기 위함입니다.


Pytype

Pytype는 Google에서 개발되었으며, Mypy와 달리 타입 설명자 대신 추론을 사용합니다. 즉, Pytype는 코드 흐름을 분석하여 타입을 결정하려고 시도하며, 타입 어노테이션에 엄격하게 의존하지 않습니다​1.
Pytype는 가능한 한 관대하게 행동하며, 런타임에서 작동하고 어떤 어노테이션도 모순되지 않는 연산이 있으면 Pytype는 그것에 대해 불평하지 않습니다.
pytype의 reveal_type(expr)을 사용해서 런타임 전에 type()과 비슷한 기능을 활용하여 디버깅/개발 가능

 

 

반응형

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

pyenv를 통한 python버전 변경  (0) 2023.12.17
venv  (0) 2023.12.17
python 스트링 인코딩 핸들링  (0) 2021.11.30
Python GUI Programming(Tkinter)  (0) 2021.01.02
파이선환경 그리고 requirements.txt  (0) 2020.09.20

+ Recent posts