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

Python代码剩余type-hint类型提示错误修复求助

错误1:None类型没有items属性

原因是my_func里的默认值判断逻辑存在语法错误,if not None永远返回True,导致attributes为None时不会被替换为空字典,后续调用items()方法时触发类型报错。
修复代码:

def my_func(attributes: None | dict[str, str] = None) -> None:
    # 修正判断逻辑,仅当attributes为None时赋值空字典
    attributes = attributes if attributes is not None else {}
    for name, value in attributes.items():
        print(name, value)

错误2:返回值类型不匹配

类型检查器无法识别exec动态写入local_dict的__HTML__变量类型,默认推导为未知类型,和方法标注的str返回值冲突。
修复代码:
首先导入类型转换工具:

from typing import Any, cast

然后修改返回逻辑,增加类型断言明确告知类型检查器值的类型:

def serve_pre_compiled(self) -> str:
    local_dict = {"obj_response": self}
    exec("file", {}, local_dict)
    return cast(str, local_dict["__HTML__"])

错误3:Response类不存在__self__属性

__self__是Python中绑定方法的内置属性,不属于类实例本身,此处属于语法误用。另外原代码的Response类也没有定义status属性,需要先补充定义。
修复代码:
首先给Response类补充status属性:

class Response:
    start_response: StartResponse
    # 补充status属性,可根据业务需求调整默认值
    status: str = "200 OK"
    def __init__(self, start_response) -> None:
        self.start_response = start_response

然后修改MyProcess里的取值逻辑,删除错误的__self__调用:

def __init__(self, environ: dict[str, Any], start_response: StartResponse) -> None:
    _ = environ
    self.obj_response = Response(start_response)
    # 直接取实例的status属性即可
    self.status = self.obj_response.status

完整修复后的代码

from typing import Any, cast
from wsgiref import simple_server
from wsgiref.types import StartResponse


def my_func(attributes: None | dict[str, str] = None) -> None:
    attributes = attributes if attributes is not None else {}
    for name, value in attributes.items():
        print(name, value)

class Response:
    start_response: StartResponse
    status: str = "200 OK"
    def __init__(self, start_response) -> None:
        self.start_response = start_response
    def serve_pre_compiled(self) -> str:
        local_dict = {"obj_response": self}
        exec("file", {}, local_dict)
        return cast(str, local_dict["__HTML__"])
    
class MyProcess:
    status: str
    obj_response: Response
    def __init__(self, environ: dict[str, Any], start_response: StartResponse) -> None:
        _ = environ
        self.obj_response = Response(start_response)
        self.status = self.obj_response.status
    def __iter__(self):
        yield b"hello world"

httpd = simple_server.make_server("", 8000, MyProcess)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:06:04