Skip to content

__new__ on abstract classes produces false positive "Cannot instantiate abstract class" #14106

Open

Description

@kedder

Bug Report

When an abstract class defines __new__ (note, not __init__) method, mypy produces error when that class is instantiated, even though __new__() does not imply instantiation.

To Reproduce

from abc import ABCMeta, abstractmethod


class Abstract(metaclass=ABCMeta):
    def __new__(cls) -> "Abstract":
        return super().__new__(Concrete)

    @abstractmethod
    def hello(self) -> int:
        ...


class Concrete(Abstract):
    def hello(self) -> int:
        return 0


x = Abstract()
print(x.hello())

Expected Behavior

No errors reported when checked with mypy. Calling a class with __new__ method shuld be effectively treated as just calling a simple method, like

def make_abstract() -> "Abstract":
    return Concrete()

Actual Behavior

error message is printed:

 error: Cannot instantiate abstract class "Abstract" with abstract attribute "hello"  [abstract]

Your Environment

  • Mypy version used: mypy-0.991
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.10.6

Activity

  1. andy-slac commented on Oct 13, 2023

    @andy-slac

    I'm seeing the same issue with Python 3.11 and mypy 1.5.1, this discussion has more details: python/typing#1487

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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