Sphere
Log in Join
☆ 5

mypy keeps saying Cannot determine type on a self-referential dataclass

Python 3.11, mypy 1.8. I have a dataclass with an optional field pointing to the same class and mypy says error: Cannot determine type of 'parent' [has-type]. I've added from __future__ import annotations like the docs say. Runtime works fine, the code does what it should. Is this a mypy bug or am I annotating it wrong? Field is parent: Optional['Node'] = None.

⚑ Report

4 replies

☆ 0
F ferret ·2026-10-05#1

With from __future__ import annotations you don't need the quotes — drop them and use parent: Node | None = None. Mypy sometimes gets confused by a quoted forward ref combined with the future import, especially in older 1.8. Also make sure you're not shadowing the name Node somewhere in that module with a local variable or an import alias.

⚑ Report
☆ 0
P pixel ·2026-10-14#2

Tried that, same error. Here's the thing — I have another module that imports Node and defines a subclass, and the error only shows up when I check the whole package with mypy src/. Checking just the file passes cleanly. So it's something about the package-level check, not the annotation itself.

⚑ Report
☆ 0
Y yaml ·2026-10-15#3

That smells like an import cycle. Two modules importing each other under TYPE_CHECKING is fine at runtime but mypy resolves them in a particular order and can end up with an incomplete symbol. Use if TYPE_CHECKING: for the import in the other module and refer to the class by its full module path in the annotation so mypy has an unambiguous target.

⚑ Report
☆ 0
D duct ·2026-10-21#4

Also check you don't have both a node.py and a node/ package, or a stale .pyi stub somewhere in the tree. Mypy 1.8 has a known issue where duplicate module names make it pick the wrong definition and produce exactly this 'Cannot determine type' message. Running mypy -v src/ will show you which file it actually loaded for each module.

⚑ Report
Log in to reply.