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