如何使用Type Hint确保两个变量始终为相同类型并让Mypy在类型不匹配时抛出错误?
The problem with your original code is that Union[int, str] lets each parameter independently be either type—Mypy has no way of knowing they need to match. To fix this, you’ll want to use a bound TypeVar to tie both parameters to the same type.
Here’s the corrected code that triggers a Mypy error when parameter types don’t match:
from typing import TypeVar # Define a TypeVar restricted to only int or str T = TypeVar("T", int, str) def add(a: T, b: T) -> str: return str(a) + str(b) # Valid cases (no Mypy errors) a: int = 1 b: int = 2 out = add(a, b) a: str = 'one' b: str = 'two' out = add(a, b) # Invalid case (Mypy will throw an error) a: int = 1 b: str = 'two' out = add(a, b) # Error: Argument 2 has incompatible type "str"; expected "int"
How this works:
TypeVar("T", int, str)creates a type variable that can only resolve to eitherintorstr.- By annotating both
aandbwithT, you’re telling Mypy that both parameters must be the same type—either bothintor bothstr. - When you mix types (like
intandstr), Mypy detects the mismatch and throws a clear error.
Bonus: Flexible unbound TypeVar
If you want the function to accept any type as long as both parameters match (not just int/str), you can define an unbound TypeVar instead:
from typing import TypeVar T = TypeVar("T") def add(a: T, b: T) -> str: return str(a) + str(b) # This will also work (both floats, no error) x: float = 3.14 y: float = 2.71 out = add(x, y) # Still errors if types don't match x: float = 3.14 y: str = "pi" out = add(x, y) # Mypy error
Just make sure your Mypy setup has strict type checking enabled (e.g., set strict = true in your mypy.ini or run mypy --strict your_file.py) to ensure all type violations are caught.
内容的提问来源于stack exchange,提问作者Jingnan Jia

