Skip to content

Using subclasses with __new__ #14426

Closed
Closed
@Viicos

Description

@Viicos

Bug Report

Noticed this behavior while working on typeddjango/djangorestframework-stubs#315, it seems that mypy isn't inferring the correct type in the following example:

from __future__ import annotations

class A:
    def __new__(cls) -> B:
        return B()

class B(A):
    pass

class C(A):
    pass

var1 = A()
reveal_type(var1) # Revealed type is "B", as excepted
var2 = C()
reveal_type(var2) # Revealed type is "C", should be "B" (pyright reports "B")

I suspect this is due to the fact that __new__ should return a subclass of the class being defined according to mypy. I think it is a reasonable idea (see #1020 (comment)) to allow arbitrary types to be allowed, altough this might not be considered a good practice. A use case can be found here (the linked PR above is trying to implement stubs for this).

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions