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

Python中正确导入SupportsWrite类型提示的方法及运行报错解决

解决方案

你遇到的问题是因为_typeshed是Python类型检查器(如mypy)的内部模块,无法在运行时导入。以下是几种正确获取SupportsWrite类型提示的方法:

方法1:使用标准库typing模块的SupportsWrite(Python 3.8+)

从Python 3.8开始,SupportsWrite正式被纳入typing模块,可以直接导入使用:

from collections import UserString
from typing import Literal, SupportsWrite

class Strool(UserString):
    def __init__(self, string) -> None:
        super().__init__(string)
    
    def print(self, end: str | None = "\n", file: SupportsWrite[str] | None = None, flush: Literal[False] = False):
        print(self.data, end=end, file=file, flush=flush)

方法2:自定义SupportsWrite协议(兼容Python 3.6+)

如果你的Python版本低于3.8,可以通过typing.Protocol自定义一个兼容的类型协议,效果和_typeshed.SupportsWrite完全一致:

from collections import UserString
from typing import Literal, Protocol, Any

class SupportsWrite(Protocol):
    def write(self, s: str) -> Any:
        ...

class Strool(UserString):
    def __init__(self, string) -> None:
        super().__init__(string)
    
    def print(self, end: str | None = "\n", file: SupportsWrite | None = None, flush: Literal[False] = False):
        print(self.data, end=end, file=file, flush=flush)

方法3:使用io.TextIO作为替代

如果你不需要极致宽泛的类型兼容,也可以直接使用io.TextIO类型,这是原生print函数file参数的官方类型提示之一:

from collections import UserString
from typing import Literal
import io

class Strool(UserString):
    def __init__(self, string) -> None:
        super().__init__(string)
    
    def print(self, end: str | None = "\n", file: io.TextIO | None = None, flush: Literal[False] = False):
        print(self.data, end=end, file=file, flush=flush)

补充说明

  • 如果你只是需要类型检查时生效,也可以使用if typing.TYPE_CHECKING条件导入,避免运行时加载_typeshed:
from collections import UserString
from typing import Literal
import typing

if typing.TYPE_CHECKING:
    from _typeshed import SupportsWrite

class Strool(UserString):
    def __init__(self, string) -> None:
        super().__init__(string)
    
    def print(self, end: str | None = "\n", file: "SupportsWrite[str]" | None = None, flush: Literal[False] = False):
        print(self.data, end=end, file=file, flush=flush)

这种方式下,类型检查器会识别SupportsWrite,但运行时不会尝试导入_typeshed,也不会报错。

内容的提问来源于stack exchange,提问作者Carlos González

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 14:57:33