You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Type Hint确保两个变量始终为相同类型并让Mypy在类型不匹配时抛出错误?

Enforce identical types for two function parameters with Python type hints

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 either int or str.
  • By annotating both a and b with T, you’re telling Mypy that both parameters must be the same type—either both int or both str.
  • When you mix types (like int and str), 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 18:12:41