How to check type compatibility when using an input module?

I use Python type prompts PEP484 to write type checking for DSL written in Python. If I have a function that expects a type Tfor one of its arguments, and it is called with a type expression S, how can I check if the call is valid? Does it use issubclass(S, T)enough? If so, why mypyhas such a complex check is_subtype? Or should I just use the version mypy?

Change . Here is an example to clarify what I mean. DSL has a function defined as:

T = TypeVar('T', float, str)
def op_add(operand1: T, operand2: T) -> T:
    "Number addition or string concatenation."
    # In this DSL, `+` cannot be used with lists
    return operand1 + operand2  # Rely on Python overloading of `+`

Then, the user enters an expression, which is analyzed in the syntax tree with a branch, which can be: node = OperatorNode('+', Literal([5.0]), Variable("abc")). We do not yet know the value of the variable abc, but lists can never be used with +, so I want to raise TypeErrorto warn the user.

If I do issubclass(typing.List[float], var), this gives me False, so I can make a mistake right away. My question is whether this check is guaranteed for different cases when I create a DSL, or if I need to use a more complex check, for examplemypy

+4
source share
1 answer

issubclass check , issubclass typing, Union, Callable, Any, generics ..

typing python , , :

issubclass(List[int], List[int])  # runtimem error
issubclass(List[int], List) # True (as expected)
issubclass(str, Union[str]) # runtime error
issubclass(Union[str], str) # True (as expected)
issubclass(Union[int, str], str) # runtime error

issubclass typing, ; , .

mypy is_subtype, typing, .

+1

All Articles