phantom types
3.0.2
Python的幻影類型將幫助您使非法國家無法說明,並通過使您能夠練習“解析,不要驗證”來避免shot彈槍解析。
$ 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]通過引入幻影類型,我們可以為函數參數定義一個前條件。
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為Checker提供了類型的檢查器。所有類型的檢查器都在乎,除非變量是Name ,否則運行時不能繼續執行超越斷言。如果我們像下面的示例中一樣將呼叫移動,則類型檢查器將給greet()調用錯誤。
joe = "Joe"
greet ( joe )
assert isinstance ( joe , Name )通過將幻影類型與Beartype或Typeguard(例如Beartype-Checker)相結合,我們可以達到與使用合同相同的安全性。
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運行類型檢查器:
$ mypy使用Goose設置襯里和格式器,安裝它後,您可以將其運行為:
# run all checks
$ goose run --select=all
# or just a single hook
$ goose run mypy --select=all除了靜態類型檢查外,還使用Pytest-Mypy-Plugins設置了該項目,以測試暴露於預期的MyPy類型的工作,這些檢查將與其餘的測試套件一起運行,但是您可以使用以下命令將它們單列出。
$ make test-typing