简体   繁体   中英

Test list with parametrized generics in python

I'm pretty sure there is some trivial answer I wan't able to keyword correctly.

Python3's typing module contains typed lists (analogous to C# generics type of things). Yet I didn't find a simple way to do this:

from typing import List                                                                                                                                          
if isinstance([1,2,3], List[int]):
    print('yay!')                                           

I know about mypy (i didn't dig into its code though) but I don't want to use it. My question is: what is the simplest and cleanest way to achieve what I want to achieve ?

You can do something like this:

def is_list_of_int(x):
    return isinstance(x, list) and all((isinstance(item, int) for item in x))

Note that only if x is a list you'd iterate over its items and check if they're of type int .

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