mypy:类型[list[Any]]”没有属性“__iter__”(不可迭代)

问题描述 投票:0回答:1

我有以下代码:

from pydantic import BaseModel


class Worker(BaseModel):
    id: int
    name: str
    status: bool = True


class WorkerList(BaseModel):
    workers = list[Worker]

    def deactivate_worker(self, worker: Worker) -> None:
        for w in self.workers:
            if w.id == worker.id:
                w.status = False
                break
        raise ValueError(
            f"Cannot deactivate worker {worker.id}: Value doesn't exist"
        )

我的代码非常简单:我只想有一个将 Bool 元素(Worker)的状态更改为 False 的函数。

mypy 突出显示

self.workers
并给我:
mypy: type[list[Any]]" has no attribute "__iter__" (not iterable)

处理这个问题的正确方法是什么?

python mypy python-typing pydantic
1个回答
0
投票

正如 user2357112 已经指出的,您错误地将注释用作分配。

from typing import List

from pydantic import BaseModel


class Worker(BaseModel):
    id: int
    name: str
    status: bool = True


class WorkerList(BaseModel):
    workers: List[Worker] = []

    def deactivate_worker(self, worker: Worker) -> None:
        for w in self.workers:
            if w.id == worker.id:
                w.status = False
                break
        raise ValueError(f"Cannot deactivate worker {worker.id}: Value doesn't exist")
© www.soinside.com 2019 - 2024. All rights reserved.