Python> = 3.5: checking type annotation at runtime

Does the module typing(or any other module) have an API for checking variable types at runtime, similarly isinstance(), but understanding the type classes defined in typing?

I would like to run something similar to:

from typing import List
assert isinstance([1, 'bob'], List[int]), 'Wrong type'
+10
source share
2 answers

There typingis no such function in the module , and most likely this will not happen.

Checking whether an object is an instance of a class that only means “this object was created by the class constructor” is a simple matter of testing some tags.

, "" , :

assert isinstance(foo, Callable[[int], str]), 'Wrong type'

foo (, a lambda), , , .

, List[int], , , .

xs = set(range(10000))
xs.add("a")
xs.pop()
assert isinstance(xs, Set[int]), 'Wrong type'

, , : , foo int. , , , .. , , , :

def foo() -> int:
    if "a".startswith("a"):
        return 1
    return "x"
+9

- typeguard. , . , , . ,

from typeguard import check_type

# Raises TypeError if there a problem
check_type('variablename', [1234], List[int])
0

Source: https://habr.com/ru/post/1675755/


All Articles