pytorch - 💡(How to fix) Fix ModuleList not recognized as Iterable by type checkers [1 pull requests]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…

Fix Action

Fixed

Code Example

import torch
from torch import nn

class MyModel(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.blocks = nn.ModuleList([nn.Linear(4, 4) for _ in range(3)])
        self.norms = nn.ModuleList([nn.LayerNorm(4) for _ in range(3)])

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        for block in self.blocks:  # ty: not-iterable
            x = block(x)
        return x

    def paired(self, x: torch.Tensor) -> torch.Tensor:
        for block, norm in zip(self.blocks, self.norms):  # ty: not-iterable
            x = norm(block(x))
        return x
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

nn.ModuleList is iterable at runtime — for block in self.blocks: and zip(self.blocks, self.other_blocks) work fine — but type checkers report not-iterable.

Reproducible code

import torch
from torch import nn

class MyModel(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.blocks = nn.ModuleList([nn.Linear(4, 4) for _ in range(3)])
        self.norms = nn.ModuleList([nn.LayerNorm(4) for _ in range(3)])

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        for block in self.blocks:  # ty: not-iterable
            x = block(x)
        return x

    def paired(self, x: torch.Tensor) -> torch.Tensor:
        for block, norm in zip(self.blocks, self.norms):  # ty: not-iterable
            x = norm(block(x))
        return x

Expected behavior

Type checkers should recognize ModuleList as iterable.

Environment

  • PyTorch 2.11, Python 3.14, ty (astral.sh type checker)

cc @albanD @mruberry @jbschlosser @walterddr @mikaylagawarecki @lolpack @maggiemoss @ndmitchell @kinto0 @samwgoldman

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

FAQ

Expected behavior

Type checkers should recognize ModuleList as iterable.

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING