Search code examples
pythonmypypython-typingpydantic

mypy: type[list[Any]]" has no attribute "__iter__" (not iterable)


I have the following code:

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"
        )

My code is really simple: I just want to have a function that changes the status of a Bool element (Worker) to False.

mypy is highlighting self.workers and giving me: mypy: type[list[Any]]" has no attribute "__iter__" (not iterable)

What is the right way to deal with this?


Solution

  • As user2357112 already noted, you've used the annotation falsely as an assignment.

    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")