简体   繁体   English

类型保护 function 第一个参数的属性类型由第二个字符串键参数确定(例如 key="Dict",然后 -> TypeGuard["Dict"])?

[英]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.

相关问题 用固定键类型(例如Enum类型)实现字典的最佳方法? - Best way to implement a dict with a fixed key type (e.g. an Enum type)? for循环只使用dict中的第一个键 - for loop only using 1st key in dict 根据第一个值和第二个键组合两个字典 - Combine two dictionaries based on value of 1st and key of 2nd mypy Dict 类型中的键类型检查 - key typechecking in mypy Dict type 为什么当我尝试定义带注释的类型 class 成员(例如列表或字典)时 PyPy 失败? - Why PyPy fails when I try to define type annotated class member (e.g. list or dict)? 如果我向函数提供一个 dict 两次,然后在其中一个 dict 中使用 del 键,由于某种原因,在第二个 dict 中删除了相同的键。 为什么? - If I provide to a function one dict two times and then del key in one of the dict, for some reason the same key are deleted in the 2nd dict. Why? 在嵌套字典中查找键以更改键的类型 - Looking for a key in a nested dict to change the type of the key argparse.add_argument() 中的 type=dict - type=dict in argparse.add_argument() TypeError:“int”类型的参数在 python 中不可迭代用于 dict - TypeError: argument of type 'int' is not iterable in python for a dict 有没有办法将特殊的非字符键作为字符串类型转换为键类型? (例如“Key.f12”到实际的keyboard.Key.f12值) - Is there a way to convert a special non-character keys as string type to a key type? (E.g. “Key.f12” to the actual keyboard.Key.f12 value)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM