如何为支持/不支持int()的对象重载Python函数?
解决方法
要实现你需要的重载类型提示,关键是利用Python类型系统的类型否定特性定义“不支持SupportsInt的类型”,具体实现如下:
最终代码(Python 3.10+)
from typing import Any, SupportsInt, overload, TypeVar # 定义泛型变量T,约束为所有不支持SupportsInt协议的类型 T = TypeVar("T", bound=~SupportsInt) @overload def to_int(value: SupportsInt) -> int: ... @overload def to_int(value: T) -> T: ... def to_int(value: Any) -> Any: try: return int(value) except TypeError: return value
关键说明
~SupportsInt是Python 3.10+引入的类型否定语法(PEP 604),专门用来表示不满足指定协议的所有类型,刚好匹配你需要的“不支持int()的对象”场景。- 若使用Python 3.10以下版本,无法直接用类型否定,可通过类型守卫辅助实现近似效果:
这种写法下,类型检查器会结合from typing import Any, SupportsInt, overload, TypeGuard def is_not_supports_int(value: Any) -> TypeGuard[object]: return not isinstance(value, SupportsInt) @overload def to_int(value: SupportsInt) -> int: ... @overload def to_int(value: object) -> object: ... def to_int(value: Any) -> Any: try: return int(value) except TypeError: return valueis_not_supports_int函数推断返回类型,但精准度略低于直接使用~SupportsInt。
内容的提问来源于stack exchange,提问作者Matt
相关产品推荐
相关产品推荐

