Skip to content

Incorrect return type for synthesised __new__ methods of NamedTuple classes #2522

@AlexWaygood

Description

@AlexWaygood

It looks like the __new__ method we synthesize for NamedTuple classes is buggy -- here's some minimal repros of some diagnostics in the ecosystem report on this PR:

from collections import namedtuple
from typing import NamedTuple, Self

class Foo(NamedTuple):
    x: int

class Bar(Foo):
    def __new__(cls) -> "Bar":
        return super().__new__(cls, x=42)  # error[invalid-return-type] "Return type does not match returned value: expected `Bar`, found `Foo`"

class Bar2(Foo):
    def __new__(cls) -> Self:
        return super().__new__(cls, x=42)  # error[invalid-return-type] "Return type does not match returned value: expected `Self@__new__`, found `Foo`"

Baz = namedtuple("Baz", "x y")

class Spam(Baz):
    def __new__(cls) -> "Spam":
        return super().__new__(cls, x=42, y=56)  # error[invalid-return-type] "Return type does not match returned value: expected `Spam`, found `Baz`"

class Spam2(Baz):
    def __new__(cls) -> Self:
        return super().__new__(cls, x=42, y=56)  # error[invalid-return-type] "Return type does not match returned value: expected `Self@__new__`, found `Baz`"

I think the return type we synthesize for these methods changed in astral-sh/ruff@3e02994. We need to infer these methods as returning Self rather than an instance of the namedtuple class, I think. cc. @charliermarsh

Originally posted by @AlexWaygood in astral-sh/ruff#22584 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingnamedtuplestyping semanticstyping-module features, spec compliance, etc

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions