How to compare types and fail if not the same #9590
Replies: 1 comment
-
The type system doesn't provide a way to enforce "type equivalency". This may sound odd, but it makes more sense when you understand some of the theory behind type systems. This section of the typing spec may be useful to read. When you use type variables in a function signature and call that function, a type checker will attempt to solve the type variables by finding some type that meets all of the constraints. In the example What you're trying to do in the above code is not a typical pattern, which explains why you're running into troubles. It's not clear to me from your code sample what you're trying to do. Type equivalency is rarely what is desired in code. Instead, type compatibility is what is normally desired. For example, if you want to ensure that the value returned by the from _typeshed import SupportsAdd
from typing import Callable
def ensure_return_type_is_addable[**P, R1, R2](fn: Callable[P, R1], other_value: SupportsAdd[R1, R2]) -> None: ...
def example_func() -> str:
return "Hello"
ensure_return_type_is_addable(example_func, "Some String") # OK
ensure_return_type_is_addable(example_func, 123) # Error |
Beta Was this translation helpful? Give feedback.
-
I want to have pyright typecheck two types, I created this small examples, but I can't seem to make it work.
Beta Was this translation helpful? Give feedback.
All reactions