![](/img/trans.png)
[英]What does typing.List<~T>[typing.Tuple[int]] mean in Python's typing lib?
[英]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
t1
和t2
会给我:
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.