Skip to content

Using Never as return type for __new__ results in classmethods not being recognised. Inferred type for class is Callable[[], NoReturn]. #16981

Open

Description

@sg495

Bug Report

If the classmethod __new__ of a class is marked as returning Never, Mypy does not recognise the existence of attributes for the class (whose type it believes to be Callable[[], NoReturn]).

To Reproduce

from typing import Never, Self

class A:
    x: int

    @classmethod
    def _new(cls, x: int) -> Self:
        instance = super().__new__(cls)
        instance.x = x
        return instance

    def __new__(cls) -> Never:
        raise TypeError("Class 'A' should not be instanced directly.")

a = A._new(10) # Mypy Error: attr-defined
# "Callable[[], NoReturn]" has no attribute "_new"

Gist URL: https://gist.github.com/mypy-play/b40fec12cb83d7683c6832320aecc4d8
Playground URL: https://mypy-play.net/?mypy=latest&python=3.12&gist=b40fec12cb83d7683c6832320aecc4d8

from typing import ClassVar, Never

class A:
    attr: ClassVar[int] = 20

    def __new__(cls) -> Never:
        raise TypeError("Class 'A' should not be instanced directly.")

a = A.attr # Mypy Error: attr-defined
# "Callable[[], NoReturn]" has no attribute "attr"

Gist URL: https://gist.github.com/mypy-play/46b45241159045b55d7dfd9d871280f1
Playground URL: https://mypy-play.net/?mypy=latest&python=3.12&gist=46b45241159045b55d7dfd9d871280f1

Expected Behavior

I expect Mypy to recognise that the classmethod A._new() can be called to produce an instance of A, or that A has a class attribute attr.

Actual Behavior

Mypy does not recognise that classmethod A._new() exists, nor that the class attribute A.attr exists.

Your Environment

  • Mypy version used: 1.7.1 (checked with 1.8.0 on playground)
  • Mypy command-line flags: --strict
  • Python version used: 3.12

Activity

  1. added
    bugmypy got something wrong
    on Mar 4, 2024
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