GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Respect explicit return type of __new__() by ilevkivskyi · Pull Request #21441 · python/mypy

Respect explicit return type of __new__() #21441

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
ilevkivskyi merged 18 commits into python:master from ilevkivskyi:new-new
May 27, 2026
+627 −111
Merged

Respect explicit return type of __new__() #21441

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
b5ea90c
Preparatory refactor
ilevkivskyi May 5, 2026
a43ecc1
Add basic logic
ilevkivskyi May 6, 2026
c930a95
Add boilerplate
ilevkivskyi May 7, 2026
8c3e017
Do not use ret_type in various special cases
ilevkivskyi May 7, 2026
b01ffea
Store precise type
ilevkivskyi May 8, 2026
b76c746
Some more tweaks
ilevkivskyi May 8, 2026
73bb465
Update docstring
ilevkivskyi May 8, 2026
4434f73
Fix one more casual ret_type
ilevkivskyi May 8, 2026
b921130
Do not leak type variables in type[T]
ilevkivskyi May 8, 2026
e356348
Merge remote-tracking branch 'upstream/master' into new-new
ilevkivskyi May 11, 2026
7916bf1
Try alternative implementation of exceptions
ilevkivskyi May 11, 2026
daba172
Fix weird stuff
ilevkivskyi May 11, 2026
f8c159b
Merge remote-tracking branch 'upstream/master' into new-new
ilevkivskyi May 22, 2026
97791b4
Address CR
ilevkivskyi May 23, 2026
4519e3f
Skip TypeVars completely; inline the call
ilevkivskyi May 23, 2026
65869e1
Merge remote-tracking branch 'upstream/master' into new-new
ilevkivskyi May 26, 2026
97534e4
Add tests; fix inference
ilevkivskyi May 26, 2026
107ede7
Some more tests
ilevkivskyi May 27, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view
Prev Previous commit
Next Next commit
Add basic logic
  • Loading branch information

Uh oh!

There was an error while loading. Please reload this page.

@ilevkivskyi
ilevkivskyi committed May 6, 2026
commit a43ecc12664ab9c126663b6bf5baceff165f88f5

Some comments aren't visible on the classic Files Changed page.

There are no files selected for viewing

7 changes: 6 additions & 1 deletion 7 mypy/applytype.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -171,12 +171,17 @@ def apply_generic_arguments(
assert isinstance(typ, TypeVarLikeType)
remaining_tvars.append(typ)

return callable.copy_modified(
applied = callable.copy_modified(
ret_type=expand_type(callable.ret_type, id_to_type),
variables=remaining_tvars,
type_guard=type_guard,
type_is=type_is,
)
if callable.instance_type is not None:
repl_type = expand_type(callable.instance_type, id_to_type)
assert isinstance(repl_type, Instance)
applied.instance_type = repl_type
return applied


def apply_poly(tp: CallableType, poly_tvars: Sequence[TypeVarLikeType]) -> CallableType | None:
Expand Down
25 changes: 15 additions & 10 deletions 25 mypy/checkmember.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -408,14 +408,19 @@ def analyze_type_callable_member_access(name: str, typ: FunctionLike, mx: Member
# Class attribute.
# TODO super?
ret_type = typ.items[0].ret_type
assert isinstance(ret_type, ProperType)
if isinstance(ret_type, TupleType):
ret_type = tuple_fallback(ret_type)
if isinstance(ret_type, TypedDictType):
ret_type = ret_type.fallback
if isinstance(ret_type, LiteralType):
ret_type = ret_type.fallback
if isinstance(ret_type, Instance):
instance_type = typ.items[0].instance_type
if instance_type is not None:
itype = instance_type
else:
assert isinstance(ret_type, ProperType)
if isinstance(ret_type, TupleType):
ret_type = tuple_fallback(ret_type)
if isinstance(ret_type, TypedDictType):
ret_type = ret_type.fallback
if isinstance(ret_type, LiteralType):
ret_type = ret_type.fallback
itype = ret_type
if isinstance(itype, Instance):
if not mx.is_operator:
# When Python sees an operator (eg `3 == 4`), it automatically translates that
# into something like `int.__eq__(3, 4)` instead of `(3).__eq__(4)` as an
Expand All @@ -432,14 +437,14 @@ def analyze_type_callable_member_access(name: str, typ: FunctionLike, mx: Member
# See https://github.com/python/mypy/pull/1787 for more info.
# TODO: do not rely on same type variables being present in all constructor overloads.
result = analyze_class_attribute_access(
ret_type, name, mx, original_vars=typ.items[0].variables, mcs_fallback=typ.fallback
itype, name, mx, original_vars=typ.items[0].variables, mcs_fallback=typ.fallback
)
if result:
return result
# Look up from the 'type' type.
return _analyze_member_access(name, typ.fallback, mx)
else:
assert False, f"Unexpected type {ret_type!r}"
assert False, f"Unexpected type {itype!r}"


def analyze_type_type_member_access(
Expand Down
4 changes: 4 additions & 0 deletions 4 mypy/expandtype.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -499,6 +499,10 @@ def visit_callable_type(self, t: CallableType) -> CallableType:
type_guard=(t.type_guard.accept(self) if t.type_guard is not None else None),
type_is=(t.type_is.accept(self) if t.type_is is not None else None),
)
if t.instance_type is not None:
repl_type = t.instance_type.accept(self)
assert isinstance(repl_type, ProperType) and isinstance(repl_type, Instance)
expanded.instance_type = repl_type
if needs_normalization:
return expanded.with_normalized_var_args()
return expanded
Expand Down
8 changes: 7 additions & 1 deletion 8 mypy/typeops.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,12 @@ def class_callable(
default_ret_type = fill_typevars(info)
explicit_type = init_ret_type if is_new else orig_self_type
if (
is_new
and explicit_type is not None
and not is_subtype(default_ret_type, explicit_type, ignore_type_params=True)
):
ret_type = explicit_type
elif (
isinstance(explicit_type, (Instance, TupleType, UninhabitedType, LiteralType))
# We have to skip protocols, because it can be a subtype of a return type
# by accident. Like `Hashable` is a subtype of `object`. See #11799
Expand All @@ -338,7 +344,7 @@ def class_callable(
# if it is actually returning a subtype of what we would return otherwise.
and is_subtype(explicit_type, default_ret_type, ignore_type_params=True)
):
ret_type: Type = explicit_type
ret_type = explicit_type
else:
ret_type = default_ret_type

Expand Down
2 changes: 2 additions & 0 deletions 2 mypy/types.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -2315,6 +2315,8 @@ def is_type_obj(self) -> bool:

def type_object(self) -> mypy.nodes.TypeInfo:
assert self.is_type_obj()
if self.instance_type is not None:
return self.instance_type.type
ret = get_proper_type(self.ret_type)
if isinstance(ret, TypeVarType):
ret = get_proper_type(ret.upper_bound)
Expand Down
76 changes: 75 additions & 1 deletion 76 test-data/unit/check-classes.test
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -7338,7 +7338,7 @@ class A:
def __new__(cls) -> int: # E: Incompatible return type for "__new__" (returns "int", but must return a subtype of "A")
pass

reveal_type(A()) # N: Revealed type is "__main__.A"
reveal_type(A()) # N: Revealed type is "builtins.int"

[case testNewReturnType4]
from typing import TypeVar, Type
Expand Down Expand Up @@ -7448,6 +7448,80 @@ class MyMetaClass(type):
class MyClass(metaclass=MyMetaClass):
pass

[case testNewReturnType13]
from typing import Protocol

class Foo(Protocol):
def foo(self) -> str: ...

class A:
def __new__(cls) -> Foo: ... # E: Incompatible return type for "__new__" (returns "Foo", but must return a subtype of "A")
Comment thread

@JukkaL JukkaL May 22, 2026

Copy link
Copy Markdown
Collaborator

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test if A is compatible with Callable[[], Foo] or Callable[[], A]? Also similarly against callback protocol.

Is it worth testing type joins involving __new__ return type overrides?

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@ilevkivskyi ilevkivskyi May 23, 2026

Copy link
Copy Markdown
Member Author

There was a problem hiding this comment.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a bunch of tests for subtyping (btw this uncovered one type combination I missed). Also added few basic things for joins. All works as expected.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

reveal_type(A()) # N: Revealed type is "__main__.Foo"
reveal_type(A().foo()) # N: Revealed type is "builtins.str"

[case testNewReturnType14]
from __future__ import annotations

class A:
def __new__(cls) -> int: raise # E: Incompatible return type for "__new__" (returns "int", but must return a subtype of "A")

class B(A):
@classmethod
def foo(cls) -> int: raise

reveal_type(B.foo()) # N: Revealed type is "builtins.int"
[builtins fixtures/classmethod.pyi]

[case testNewReturnType15]
from typing import Generic, Type, TypeVar

T = TypeVar("T")

class A(Generic[T]):
def __new__(cls) -> B[int]: ...
@classmethod
def foo(cls: Type[A[T]]) -> T: ...

class B(A[T]): ...

# The Never without error is not ideal, but matches the behavior without custom __new__().
reveal_type(B.foo()) # N: Revealed type is "Never"
reveal_type(B[str].foo()) # N: Revealed type is "builtins.str"

class C(A[str]): ...

reveal_type(C.foo()) # N: Revealed type is "builtins.str"
[builtins fixtures/classmethod.pyi]

[case testNewReturnType16]
from typing import Generic, TypeVar

T = TypeVar("T")
class A(Generic[T]):
def __new__(cls, *args, **kwargs) -> T: # E: "__new__" must return a class instance (got "T")
...

class Model:
pass

reveal_type(A[Model]()) # N: Revealed type is "__main__.Model"

class B(A[Model]):
pass

reveal_type(B()) # N: Revealed type is "__main__.Model"
[builtins fixtures/dict.pyi]

[case testNewReturnType17]
class C:
def __new__(self) -> D:
return D()

class D(C):
x: int

C.x # E: "type[C]" has no attribute "x"

[case testMetaclassPlaceholderNode]
from sympy.assumptions import ManagedProperties
Expand Down
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.