5

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.

2
  • 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 Commented Nov 22, 2019 at 0:59
  • 1
    Possible duplicate of extracting data from typing types Commented Nov 22, 2019 at 1:03

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.