简体   繁体   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]

I want to execute different code depending on the type of my t .我想根据t的类型执行不同的代码。

I've got the follwing types:我有以下类型:

from pydantic import BaseModel
from typing import List

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

and

t1 = Person
t2 = List[Person]

now I want to check if my variable tX is if of a list type or a normal type.现在我想检查我的变量 tX 是列表类型还是普通类型。 How can I do that?我怎样才能做到这一点?

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

t1 and t2 would give me: t1t2会给我:

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

You don't to import the typing library.您不需要导入打字库。 Just evaluate this type(t) == list.只需评估此 type(t) == 列表。

The most pythonic way of doing it is using the built-in function isinstance :最pythonic的方法是使用内置的 function isinstance

if isinstance(t, list)

At least according to PEP-8 :至少根据PEP-8

Object type comparisons should always use isinstance() instead of comparing types directly Object 类型比较应该总是使用 isinstance() 而不是直接比较类型


If you want to check an inheritance from typing.List you should be aware that a list doesn't come from typing.List , that's only a way of representing it in type hints.如果你想从typing.List你应该知道list不是来自typing.List ,这只是在类型提示中表示它的一种方式。

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

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