繁体   English   中英

如何检查我的类型 t 是否被 typing.List 包围? 例如检查 int 和 List[int] 之间的区别

[英]How to check if my type t is surrounded by typing.List or not? For example check the difference between int and List[int]

我想根据t的类型执行不同的代码。

我有以下类型:

from pydantic import BaseModel
from typing import List

class Person(BaseModel):
    name: str
    id: int

t1 = Person
t2 = List[Person]

现在我想检查我的变量 tX 是列表类型还是普通类型。 我怎样才能做到这一点?

def check_if_list(t):
    if type(t) == List:  # <- this doesn't work how can i do this check
        print('LIST') # some code
    else:
        print('NO LIST') # some code

t1t2会给我:

check_if_list(t1)  # prints NO LIST
check_if_list(t2)  # prints LIST

您不需要导入打字库。 只需评估此 type(t) == 列表。

最pythonic的方法是使用内置的 function isinstance

if isinstance(t, list)

至少根据PEP-8

Object 类型比较应该总是使用 isinstance() 而不是直接比较类型


如果你想从typing.List你应该知道list不是来自typing.List ,这只是在类型提示中表示它的一种方式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM