[英]a type guard function that 1st argument's attribute type is determined by the 2nd string key argument (e.g. key="Dict", then -> TypeGuard["Dict"])?
I tried to parse a JSON data into a Python Pydantic class object.我试图将 JSON 数据解析为 Python Pydantic class ZA8CFDE6331BD59EB2AC96F8661 The problem is that the data is like问题是数据就像
class Data(BaseModel):
val: Union[Dict, SubData1, SubData2]
key: str # e.g. "dict_type", "sub_data_type", "sub_data_type2"
I'm thinking to make a type guard function ( check_type
) and use it like below:我正在考虑制作一个类型保护 function ( check_type
)并像下面这样使用它:
if check_type(data, "dict_type"):
value = data.val ## type checker will automatically know it is Dict
elif check_type(data, "sub_data_type"):
value = data.val ## type checker will automatically know it is SubData1
It will allow my IDE to have better maintainability.这将使我的 IDE 具有更好的可维护性。 Is it doable?可行吗?
import typing
@typing.overload
def check_type_1(data: typing.Any, typename: typing.Literal["dict"]) -> typing.TypeGuard[dict]:
...
@typing.overload
def check_type_1(data: typing.Any, typename: typing.Literal["list"]) -> typing.TypeGuard[list]:
...
def check_type_1(data: typing.Any, typename: str) -> bool:
if typename == "dict":
return isinstance(data, dict)
elif typename == "list":
return isinstance(data, list)
else:
raise NotImplementedError
def test2():
x: typing.Any = 1
if check_type_1(x, "dict"):
print(f"x={x} is dict")
elif check_type_1(x, "list"):
print(f"x={x} is list")
else:
print(f"x={x} is {type(x)}")
if __name__ == "__main__":
test2()
Try this code in Python 3.10.在 Python 3.10 中尝试此代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.