3

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.

Chao Peng
  • 179
  • 8
  • I left an empty str there actually want to mean any list or even anything. The problem is not the first variable of isinstance, but the second one. However, I re-edit the problem to make it more clear – Chao Peng Nov 22 '19 at 00:59
  • 1
    Possible duplicate of [extracting data from typing types](https://stackoverflow.com/questions/51171908/extracting-data-from-typing-types) – user8408080 Nov 22 '19 at 01:03

1 Answers1

2

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)
Chao Peng
  • 179
  • 8