jsonschema typed
1.0.0
该软件包提供了一种基于jsonschema -schemas自动产生类型注释的方法。
并非所有由jsonschema所涵盖的概念都可以在Python打字注释中表达。但是,大多数事情都会像您期望的那样工作。大多数类型都是微不足道的( integer , number , string , array , boolean和null )。有趣的类型是object ,该对象被翻译成TypedDict 。
警告:这是基于Mypy插件系统,该系统据说没有向后兼容保证。新版本的mypy可能不会立即得到支持。
JSON模式:
{
"$schema" : " http://json-schema.org/draft-07/schema# " ,
"$id" : " http://foo.qwerty/some/schema# " ,
"title" : " Foo Schema " ,
"type" : " object " ,
"properties" : {
"title" : {
"type" : " string "
},
"awesome" : {
"type" : " number "
}
},
"required" : [ " title " ]
}打字:
from typing import TYPE_CHECKING
from jsonschema_typed import JSONSchema
data : JSONSchema [ "path/to/schema.json" ] = { "title" : "baz" }
if TYPE_CHECKING :
reveal_type ( data ) # Revealed type is 'TypedDict('FooSchema', {'title': builtins.str,
# 'awesome'?: Union[builtins.int, builtins.float]})'
data [ "description" ] = "there is no description" # TypedDict "FooSchema" has no key 'description'
data [ "awesome" ] = 42
data [ "awesome" ] = None # Argument 2 has incompatible type "None"; expected "Union[int, float]"您还可以获取模式的部分类型以及阵列中的元素类型。看看测试用例以获取更多用法示例。
pip install jsonschema-typed您还需要在mypy.ini配置文件中启用插件:
# mypy.ini
[ mypy ]
plugins = j sonschema_typed.plugin, jsonschema_typed.optional_typed_dict
# Due to a quirk of how these type hints are generated, mypy's caching breaks.
# Disabling caching might be required.
cache_dir = / dev/null 以上装置解决了依赖项,这些依赖项由mypy和jsonschema (自然)组成。测试已通过版本进行:
可能还会有些较旧的版本。如果您需要其他版本,请报告问题。
additionalProperties在TypedDict中并没有等效。default关键字不支持;但请参阅:Python/Mypy#6131。"#" )在支持嵌套的前向引用之前无法真正正常工作。请参阅:Python/Mypy#731。