简体   繁体   中英

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]?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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