[英]Python Type Hinting - hint a filtered list understand the type
I have two classes instances in a list:我在列表中有两个类实例:
from typing import List, Union
class A:
my_type: str = 'A'
class B:
my_type: str = 'B'
my_list: List[Union[A, B]] = [A(),A(),B(),B()]
As: List[A] = [a for a in my_list if a.my_type == 'A']
def function_that_gets_only_array_of_As(arr: List[A]):
print(arr)
function_that_gets_only_array_of_As(As) # this yields a type hint error
how would I hint that As is of type List[A]?我将如何暗示 As 属于 List[A] 类型?
You can use a type assertion/cast to override the inferred type:您可以使用类型断言/转换来覆盖推断的类型:
from typing import cast
As = cast(List[A], [...])
It's basically up to you there to ensure that your types are what you declare them to be.基本上由你来确保你的类型是你声明的类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.