Python의 Phantom 유형은 불법 상태를 대표 할 수없는 상태로 만들고 "구문 분석, 검증하지 말라"는 연습을 할 수있게함으로써 산탄 총 구문 분석을 피할 수 있도록 도와줍니다.
$ python3 -m pip install phantom-types기능을 활성화하거나 타사 라이브러리의 호환 버전을 설치하는 데 사용할 수있는 몇 가지 추가 기능이 있습니다.
| 추가 이름 | 특징 |
|---|---|
[dateutil] | Python-Dateutil을 설치합니다. TZAware 및 TZNaive 사용한 문자열을 구문 분석하는 데 필요합니다. |
[phonenumbers] | 포도주를 설치합니다. phantom.ext.phonenumbers 사용해야합니다. |
[pydantic] | Pydantic을 설치합니다. |
[hypothesis] | 가설을 설치합니다. |
[all] | 위의 모든 것을 설치합니다. |
$ python3 -m pip install phantom-types[all]Phantom 유형을 도입함으로써 우리는 함수 인수에 대한 사전 조건을 정의 할 수 있습니다.
from phantom import Phantom
from phantom . predicates . collection import contained
class Name ( str , Phantom , predicate = contained ({ "Jane" , "Joe" })): ...
def greet ( name : Name ):
print ( f"Hello { name } !" )이제 이것은 유효한 전화가 될 것입니다.
greet ( Name . parse ( "Jane" ))... 그리고 이것도 마찬가지입니다.
joe = "Joe"
assert isinstance ( joe , Name )
greet ( joe )그러나 이것은 정적 유형 검사 오류를 산출합니다.
greet ( "bird" ) 분명히, 첫 번째 예제가 통과하는 이유는 유형 검사기가 어떻게 든 우리의 술어에 대해 마술처럼 알고 있기 때문이 아니라, 유형 검사기에게 assert 통해 증거를 제공했기 때문입니다. 모든 유형의 체커는 변수가 Name 아니라면 런타임이 어설 션을 계속 실행할 수 없다는 것입니다. 아래 예제에서와 같이 통화를 이동하면 유형 체커가 greet() 호출에 오류가 발생합니다.
joe = "Joe"
greet ( joe )
assert isinstance ( joe , Name )Phantom 유형을 Beartype 또는 TypeGuard와 같은 런타임 유형-체커와 결합함으로써 계약 사용으로 얻을 수있는 것과 동일한 수준의 보안을 달성 할 수 있습니다.
import datetime
from beartype import beartype
from phantom . datetime import TZAware
@ beartype
def soon ( dt : TZAware ) -> TZAware :
return dt + datetime . timedelta ( seconds = 10 ) soon 기능은 인수와 반환 값이 모두 시간대 인식, 예를 들어 사전 및 사후 조건임을 확인할 것입니다.
Phantom 유형은 Pydantic과 함께 사용할 준비가되었으며 통합 된 지원을 제공합니다. Phantom 의 서브 클래스는 Pydantic의 검증 및 스키마 생성과 함께 작동합니다.
class Name ( str , Phantom , predicate = contained ({ "Jane" , "Joe" })):
@ classmethod
def __schema__ ( cls ) -> Schema :
return super (). __schema__ () | {
"description" : "Either Jane or Joe" ,
"format" : "custom-name" ,
}
class Person ( BaseModel ):
name : Name
created : TZAware
print ( json . dumps ( Person . schema (), indent = 2 ))위의 코드는 다음 Jsonschema를 출력합니다.
{
"title" : " Person " ,
"type" : " object " ,
"properties" : {
"name" : {
"title" : " Name " ,
"description" : " Either Jane or Joe " ,
"format" : " custom-name " ,
"type" : " string "
},
"created" : {
"title" : " TZAware " ,
"description" : " A date-time with timezone data. " ,
"type" : " string " ,
"format" : " date-time "
}
},
"required" : [ " name " , " created " ]
}가급적 VirtualEnV에서 개발 요구 사항을 설치합니다.
$ python3 -m pip install .[all,test,type-check]실행 테스트 :
$ pytest
# or
$ make test유형 검사기 실행 :
$ mypyLinters와 Formatters는 거위로 설정되며 설치 한 후에는 다음과 같이 실행할 수 있습니다.
# run all checks
$ goose run --select=all
# or just a single hook
$ goose run mypy --select=all정적 유형 확인 외에도 프로젝트는 Pytest-Mypy-Plugins와 함께 설정되어 MyPy 유형이 예상대로 노출 된 테스트를 설정하면 이러한 검사는 나머지 테스트 스위트와 함께 실행되지만 다음 명령으로 단일을 만듭니다.
$ make test-typing