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 tests; fix inference
  • Loading branch information

Uh oh!

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

@ilevkivskyi
ilevkivskyi committed May 26, 2026
commit 97534e40c67c0d7b1d4b57a296e6d670813be804

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

There are no files selected for viewing

19 changes: 18 additions & 1 deletion 19 mypy/constraints.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import mypy.typeops
from mypy.argmap import ArgTypeExpander
from mypy.erasetype import erase_typevars
from mypy.expandtype import expand_type_by_instance
from mypy.maptype import map_instance_to_supertype
from mypy.nodes import (
ARG_OPT,
Expand Down Expand Up @@ -1221,6 +1222,20 @@ def visit_callable_type(self, template: CallableType) -> list[Constraint]:
elif isinstance(self.actual, Overloaded):
return self.infer_against_overloaded(self.actual, template)
elif isinstance(self.actual, TypeType):
# This matches the corresponding logic in subtypes.py.
item = self.actual.item
if isinstance(item, TupleType):
item = mypy.typeops.tuple_fallback(item)
if isinstance(item, Instance):
constructor = mypy.typeops.type_object_type(item.type)
constructor = expand_type_by_instance(constructor, item)
# Only consider return type to match historic behavior (see below).
if isinstance(constructor, CallableType):
return infer_constraints(
template.ret_type, constructor.ret_type, self.direction
)
elif isinstance(constructor, Overloaded):
return self.infer_against_overloaded(constructor, template, ret_only=True)
return infer_constraints(template.ret_type, self.actual.item, self.direction)
elif isinstance(self.actual, Instance):
# Instances with __call__ method defined are considered structural
Expand All @@ -1236,14 +1251,16 @@ def visit_callable_type(self, template: CallableType) -> list[Constraint]:
return []

def infer_against_overloaded(
self, overloaded: Overloaded, template: CallableType
self, overloaded: Overloaded, template: CallableType, ret_only: bool = False
) -> list[Constraint]:
# Create constraints by matching an overloaded type against a template.
# This is tricky to do in general. We cheat by only matching against
# the first overload item that is callable compatible. This
# seems to work somewhat well, but we should really use a more
# reliable technique.
item = find_matching_overload_item(overloaded, template)
if ret_only:
return infer_constraints(template.ret_type, item.ret_type, self.direction)
return infer_constraints(template, item, self.direction)

def visit_tuple_type(self, template: TupleType) -> list[Constraint]:
Expand Down
31 changes: 31 additions & 0 deletions 31 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 @@ -7669,6 +7669,37 @@ reveal_type(join(B, A)) # N: Revealed type is "def () -> __main__.Base"
j = join(A, B)
x: int = j # E: Incompatible types in assignment (expression has type "type[Base2]", variable has type "int")
Comment thread

@JukkaL JukkaL May 26, 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.

What about testing isinstance narrowing with a type that has an explicit __new__ return type?

Sorry, something went wrong.

Uh oh!

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

All reactions

[case testNewReturnTypeCallableInference]
from typing import Callable, TypeVar

class A:
def __new__(cls) -> int: ... # type: ignore

T = TypeVar("T")
def foo(f: Callable[[], T]) -> T: ...

ta: type[A]
reveal_type(foo(A)) # N: Revealed type is "builtins.int"
reveal_type(foo(ta)) # N: Revealed type is "builtins.int"

[case testNewReturnTypeCallableNarrowing]
from typing import Callable, TypeVar

class A: ...

class B(A):
more = 1
def __new__(cls) -> A: ... # type: ignore

x: A
if isinstance(x, B):
reveal_type(x) # N: Revealed type is "__main__.B"

tx: type[A]
if issubclass(tx, B):
reveal_type(tx) # N: Revealed type is "type[__main__.B]"
[builtins fixtures/isinstancelist.pyi]

[case testMetaclassPlaceholderNode]
from sympy.assumptions import ManagedProperties
from sympy.ops import AssocOp
Expand Down
32 changes: 32 additions & 0 deletions 32 test-data/unit/check-incremental.test
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -8084,3 +8084,35 @@ tmp/m.py:3: note: Revealed type is "TypedDict('lib.A', {'x': builtins.int})"
[out2]
tmp/lib.py:4: error: Name "A" already defined (possibly by an import)
tmp/m.py:3: note: Revealed type is "TypedDict('lib.A', {'x': builtins.int})"

[case testNewReturnTypeIncremental]
import m
[file m.py]
from lib import C

reveal_type(C().ta)
x: int = C().ta
reveal_type(C().ta.x)
[file m.py.2]
from lib import C

# touch
reveal_type(C().ta)
x: int = C().ta
reveal_type(C().ta.x)
[file lib.py]
class A:
x = "test"
def __new__(cls) -> int: ... # type: ignore

class C:
def __init__(self) -> None:
self.ta = A
[out]
tmp/m.py:3: note: Revealed type is "def () -> builtins.int"
tmp/m.py:4: error: Incompatible types in assignment (expression has type "type[A]", variable has type "int")
tmp/m.py:5: note: Revealed type is "builtins.str"
[out2]
tmp/m.py:4: note: Revealed type is "def () -> builtins.int"
tmp/m.py:5: error: Incompatible types in assignment (expression has type "type[A]", variable has type "int")
tmp/m.py:6: note: Revealed type is "builtins.str"
Loading
Oops, something went wrong.

Uh oh!

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

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.