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

如何为支持/不支持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 value
    
    这种写法下,类型检查器会结合is_not_supports_int函数推断返回类型,但精准度略低于直接使用~SupportsInt。

内容的提问来源于stack exchange,提问作者Matt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:22:12