Chao Peng
Chao Peng

Reputation: 309

How to check whether a variable is an instance of a subscripted generics defined in typing?

i.e. How to make this work?

python doesn't allow this:

from typing import List
isinstance(["a", "b"], List[str])
# TypeError: Subscripted generics cannot be used with class and instance checks

possible solution:

from typing import List
import third_party_package
third_party_package.isinstance(["a", "b"], List[str])

I tried mypy, but mypy seems can only be called by command line. I have no idea how to make it work by python code.

Upvotes: 5

Views: 2523

Answers (1)

Chao Peng
Chao Peng

Reputation: 309

Thanks to @user8408080, I find typeguard, but that is not exactly what I want. then I use typeguard to search through stack overflow, and find two more similar library from here:

Finally, I got what I want as follows

import typesentry
from typing import List

string_list = ['nobody', 'expects', 'the', 'spanish', 'inqusition']
string_list_class = List[str]

tc1 = typesentry.Config()
is_typed = tc1.is_type  # equivalent of isinstance()

is_typed(string_list,string_list_class)

Upvotes: 3

Related Questions