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 — Fix various crashes on recursive type variable defaults by ilevkivskyi · Pull Request #21491 · python/mypy

Conversation

@ilevkivskyi

@ilevkivskyi ilevkivskyi commented May 15, 2026 •
edited
Loading

Uh oh!

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

Copy link
Copy Markdown
Member

Fixes #17716
Fixes #20698
Fixes #21128
Fixes #21269

Although the main idea is relatively simple (replace explicit type variable defaults with Any in cases where they would cause infinite recursion), this required a lot of "plumbing", because:

  • We always call fix_instance() eagerly and early.
  • There are four different cases to handle (classes vs aliases, and old style vs new style).
  • Relevant pieces of information are available in "distant" places (and I don't want to add any global state).

Some additional notes:

  • I clean-up some weirdness with deferral on type variable defaults with placeholders (especially in type aliases).
  • I remove an unwarranted get_proper_type() call during semantic analysis.
  • Now we handle rare edge case of unused alias type variables in BoolTypeQuery (possible with new style aliases).
  • Type variable defaults should be considered in __eq__() to correctly detect progress.

Sorry, something went wrong.

Uh oh!

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

All reactions
ilevkivskyi added 5 commits May 10, 2026 23:08
@ilevkivskyi
Add limited implementation
7a07960
@ilevkivskyi
Merge remote-tracking branch 'upstream/master' into fix-tv-default-cr…
8efda98
…ashes
@ilevkivskyi
Support non-recursive incomplete defaults
cddf39f
@ilevkivskyi
Add more tests, fix new style classes
dbe1c63
@ilevkivskyi
Some cleanup
8597fc7
@ilevkivskyi
ilevkivskyi requested review from JukkaL, cdce8p and hauntsaninja May 15, 2026 15:12
ilevkivskyi added 2 commits May 15, 2026 16:27
@ilevkivskyi
Fix self-compilation
43586b6
@ilevkivskyi
Try better self-compilation fix
e456cbe
@github-actions

This comment has been minimized.

Sign in to view
@ilevkivskyi

ilevkivskyi commented May 15, 2026

Copy link
Copy Markdown
Member Author

Hm, it looks like something went wrong. I will take a look later today or tomorrow.

All reactions

Sorry, something went wrong.

Uh oh!

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

ilevkivskyi added 2 commits May 15, 2026 19:15
@ilevkivskyi
Fix base classes
0f47216
@ilevkivskyi
Add custom note in case Any was forced
c0e7eda
@github-actions

This comment has been minimized.

Sign in to view
@ilevkivskyi

ilevkivskyi commented May 16, 2026

Copy link
Copy Markdown
Member Author

OK, this is ready for review now.

Btw the mypy_primer changes in steam.py are good illustration of why I took this (more complex) approach rather than trying to tune mark_incomplete() usage.

All reactions

Sorry, something went wrong.

Uh oh!

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

@ilevkivskyi

ilevkivskyi commented May 16, 2026

Copy link
Copy Markdown
Member Author

Oh, it looks like this fixes #20698 as well.

All reactions

Sorry, something went wrong.

Uh oh!

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

@ilevkivskyi
Merge remote-tracking branch 'upstream/master' into fix-tv-default-cr…
3d3a217
…ashes
@ilevkivskyi

ilevkivskyi commented May 20, 2026

Copy link
Copy Markdown
Member Author

@JukkaL @hauntsaninja @cdce8p Ping here.

All reactions

Sorry, something went wrong.

Uh oh!

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

@github-actions

This comment has been minimized.

Sign in to view
@ilevkivskyi
Merge remote-tracking branch 'upstream/master' into fix-tv-default-cr…
459adb1
…ashes
@github-actions

This comment has been minimized.

Sign in to view
@ilevkivskyi

ilevkivskyi commented May 22, 2026

Copy link
Copy Markdown
Member Author

@JukkaL this is another PR in case you missed it.

All reactions

Sorry, something went wrong.

Uh oh!

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

@ilevkivskyi
Merge remote-tracking branch 'upstream/master' into fix-tv-default-cr…
c6c8493
…ashes
@github-actions

github-actions Bot commented May 24, 2026

Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

steam.py (https://github.com/Gobot1234/steam.py)
- steam/_const.py:29: error: Module "steam.clan" has no attribute "Clan"  [attr-defined]
- steam/_const.py:30: error: Module "steam.group" has no attribute "Group"  [attr-defined]
- steam/types/user.py:16: error: Module "steam.user" has no attribute "User"  [attr-defined]
- steam/types/user.py:139: error: Cannot resolve name "Author" (possible cyclic definition)  [misc]
- steam/invite.py:16: error: Module "steam.clan" has no attribute "Clan"  [attr-defined]
- steam/invite.py:19: error: Module "steam.group" has no attribute "Group"  [attr-defined]
- steam/invite.py:21: error: Module "steam.user" has no attribute "User"  [attr-defined]
- steam/invite.py:118: error: Cannot resolve name "ChatGroupInvite" (possible cyclic definition)  [misc]
- steam/ext/commands/errors.py:12: error: Module "steam.ext.commands.commands" has no attribute "Command"; maybe "command"?  [attr-defined]
- steam/role.py:15: error: Module "steam.chat" has no attribute "ChatGroup"  [attr-defined]
- steam/role.py:15: error: Module "steam.chat" has no attribute "Member"; maybe "MemberT"?  [attr-defined]
- steam/role.py:16: error: Module "steam.clan" has no attribute "Clan"  [attr-defined]
- steam/role.py:17: error: Module "steam.group" has no attribute "Group"  [attr-defined]
- steam/app.py:41: error: Module "steam.clan" has no attribute "Clan"  [attr-defined]
- steam/app.py:42: error: Module "steam.friend" has no attribute "Friend"  [attr-defined]
- steam/app.py:396: error: Cannot resolve Self upper bound (possible cyclic definition)  [misc]
- steam/trade.py:27: error: Module "steam.friend" has no attribute "Friend"  [attr-defined]
- steam/trade.py:30: error: Module "steam.user" has no attribute "User"  [attr-defined]
- steam/reaction.py:22: error: Module "steam.message" does not explicitly export attribute "Message"  [attr-defined]
- steam/package.py:29: error: Module "steam.user" has no attribute "User"  [attr-defined]
- steam/profile.py:26: error: Module "steam.clan" has no attribute "Clan"  [attr-defined]
- steam/profile.py:27: error: Module "steam.friend" has no attribute "Friend"  [attr-defined]
- steam/profile.py:32: error: Module "steam.user" has no attribute "User"  [attr-defined]
- steam/abc.py:37: error: Module "steam.clan" has no attribute "Clan"  [attr-defined]
- steam/abc.py:38: error: Module "steam.comment" has no attribute "Comment"; maybe "CommentID" or "Commentable"?  [attr-defined]
- steam/abc.py:40: error: Module "steam.group" has no attribute "Group"  [attr-defined]
- steam/abc.py:43: error: Module "steam.message" has no attribute "UserMessage"; maybe "Message" or "UserMessageAuthorT"?  [attr-defined]
- steam/abc.py:49: error: Module "steam.user" has no attribute "User"  [attr-defined]
- steam/abc.py:58: error: Cannot resolve name "Message" (possible cyclic definition)  [misc]
- steam/abc.py:58: error: TypeVar "bound" must be a type  [misc]
- steam/abc.py:58: error: TypeVar "default" must be a type  [misc]
- steam/user.py:33: error: Module "steam.channel" has no attribute "UserChannel"; maybe "Channel"?  [attr-defined]
- steam/user.py:34: error: Module "steam.friend" has no attribute "Friend"  [attr-defined]
- steam/user.py:36: error: Module "steam.message" has no attribute "UserMessage"; maybe "Message" or "UserMessageAuthorT"?  [attr-defined]
- steam/published_file.py:28: error: Module "steam.friend" has no attribute "Friend"  [attr-defined]
+ steam/published_file.py:509: error: List comprehension has incompatible type List[Friend | None]; expected List[Friend]  [misc]
- steam/event.py:22: error: Module "steam.clan" has no attribute "Clan"  [attr-defined]
- steam/chat.py:37: error: Module "steam.clan" has no attribute "Clan"  [attr-defined]
- steam/chat.py:38: error: Module "steam.group" has no attribute "Group"  [attr-defined]
- steam/chat.py:41: error: Module "steam.message" has no attribute "ClanMessage"; maybe "ChatMessage", "Message", or "ClanMessageAuthorT"?  [attr-defined]
- steam/chat.py:41: error: Module "steam.message" has no attribute "GroupMessage"; maybe "GroupMessageAuthorT"?  [attr-defined]
- steam/chat.py:45: error: Cannot resolve name "Chat" (possible cyclic definition)  [misc]
- steam/chat.py:45: error: TypeVar "bound" must be a type  [misc]
- steam/chat.py:45: error: TypeVar "default" must be a type  [misc]
- steam/chat.py:46: error: Cannot resolve name "Member" (possible cyclic definition)  [misc]
- steam/chat.py:46: error: TypeVar "bound" must be a type  [misc]
- steam/chat.py:46: error: TypeVar "default" must be a type  [misc]
- steam/chat.py:412: error: Unused "type: ignore" comment  [unused-ignore]
+ steam/chat.py:402: error: List item 0 has incompatible type "type[ClanT]"; expected "type[Group] | type[None] | type[Clan]"  [list-item]
+ steam/chat.py:402: error: List item 1 has incompatible type "type[GroupT]"; expected "type[Group] | type[None] | type[Clan]"  [list-item]
+ steam/chat.py:428: error: Argument 1 to "append" of "list" has incompatible type "GroupMessage[PartialMember | GroupMember] | ClanMessage[PartialMember | ClanMember]"; expected "ChatMessageT"  [arg-type]
- steam/message.py:15: error: Module "steam.channel" has no attribute "ClanChannel"; maybe "Channel"?  [attr-defined]
- steam/message.py:15: error: Module "steam.channel" has no attribute "GroupChannel"; maybe "GroupChannelProtos"?  [attr-defined]
- steam/message.py:15: error: Module "steam.channel" has no attribute "UserChannel"; maybe "Channel"?  [attr-defined]
- steam/message.py:16: error: Module "steam.clan" has no attribute "Clan"  [attr-defined]
- steam/message.py:16: error: Module "steam.clan" has no attribute "ClanMember"  [attr-defined]
- steam/message.py:18: error: Module "steam.group" has no attribute "Group"  [attr-defined]
- steam/message.py:18: error: Module "steam.group" has no attribute "GroupMember"  [attr-defined]
- steam/channel.py:16: error: Module "steam.clan" has no attribute "Clan"  [attr-defined]
- steam/channel.py:18: error: Module "steam.group" has no attribute "Group"  [attr-defined]
- steam/group.py:24: error: Cannot resolve name "Group" (possible cyclic definition)  [misc]
- steam/clan.py:55: error: TypeVar "bound" must be a type  [misc]
- steam/clan.py:58: error: Cannot resolve name "Clan" (possible cyclic definition)  [misc]
- steam/state.py:1476: error: Unused "type: ignore" comment  [unused-ignore]
- steam/state.py:1515: error: Unused "type: ignore" comment  [unused-ignore]
+ steam/state.py:2400: error: Argument 1 to "add" of "set" has incompatible type "CommentID | _ReadOnlyProto[CommentID]"; expected "int"  [arg-type]
- steam/client.py:74: error: Module "steam.ext.commands.bot" has no attribute "Bot"  [attr-defined]
+ steam/client.py:1290: error: Redundant cast to "list[TradeOffer[MovedItem[User], MovedItem[ClientUser], User]]"  [redundant-cast]
+ steam/client.py:1906: error: The erased type of self "steam.ext.commands.bot.Bot" is not a supertype of its class "steam.client.Client"  [misc]
+ steam/client.py:1915: error: The erased type of self "steam.ext.commands.bot.Bot" is not a supertype of its class "steam.client.Client"  [misc]
- steam/ext/commands/cooldown.py:16: error: Module "steam.ext.commands.context" has no attribute "Context"  [attr-defined]
- steam/ext/commands/cooldown.py:71: error: Argument 1 to "BucketTypeType" has incompatible type "Any | Role | RoleID | None"; expected "int | None"  [arg-type]
+ steam/ext/commands/cooldown.py:71: error: Argument 1 to "BucketTypeType" has incompatible type "Clan | Role | RoleID | None"; expected "int | None"  [arg-type]
+ steam/ext/commands/cooldown.py:77: error: Argument 1 to "BucketTypeType" has incompatible type "Clan | bool | None"; expected "int | None"  [arg-type]
- steam/ext/commands/context.py:21: error: Module "steam.ext.commands.bot" has no attribute "Bot"  [attr-defined]
- steam/ext/commands/context.py:22: error: Module "steam.ext.commands.commands" has no attribute "Command"; maybe "command"?  [attr-defined]
- steam/ext/commands/converters.py:44: error: Module "steam.ext.commands.bot" has no attribute "Bot"  [attr-defined]
- steam/ext/commands/commands.py:47: error: Module "steam.ext.commands.bot" has no attribute "Bot"  [attr-defined]
- steam/ext/commands/commands.py:48: error: Module "steam.ext.commands.cog" has no attribute "Cog"; maybe "CogT"?  [attr-defined]
- steam/ext/commands/commands.py:66: error: Cannot resolve name "CheckType" (possible cyclic definition)  [misc]
- steam/ext/commands/commands.py:69: error: Cannot resolve name "Command" (possible cyclic definition)  [misc]
- steam/ext/commands/commands.py:111: error: Cannot resolve name "GroupMixin" (possible cyclic definition)  [misc]
- steam/ext/commands/commands.py:111: error: Cannot resolve name "Group" (possible cyclic definition)  [misc]
- steam/ext/commands/commands.py:117: error: Cannot resolve name "Command" (possible cyclic definition)  [misc]
- steam/ext/commands/commands.py:117: error: TypeVar "bound" must be a type  [misc]
- steam/ext/commands/commands.py:117: error: TypeVar "default" must be a type  [misc]
- steam/ext/commands/commands.py:575: error: Cannot resolve name "CallbackT" (possible cyclic definition)  [misc]
- steam/ext/commands/commands.py:732: error: Unused "type: ignore" comment  [unused-ignore]
- steam/ext/commands/commands.py:831: error: Incompatible return value type (got "Any | Command[Any, Any, Any]", expected "C")  [return-value]
+ steam/ext/commands/commands.py:831: error: Incompatible return value type (got "C | Command[Any, Any, Any]", expected "C")  [return-value]
- steam/ext/commands/help.py:35: error: Redundant cast to "CommandKwargs[Any]"  [redundant-cast]
+ steam/ext/commands/help.py:35: error: Redundant cast to "CommandKwargs[Command[Cog[Bot] | Bot | None, [VarArg(Any), KwArg(Any)], Any]]"  [redundant-cast]
- steam/ext/commands/help.py:138: note:          def on_error(self, ctx: Context[Any], error: Exception) -> Coroutine[Any, Any, None]
+ steam/ext/commands/help.py:138: note:          def on_error(self, ctx: Context[Bot], error: Exception) -> Coroutine[Any, Any, None]
- steam/ext/commands/cog.py:20: error: Module "steam.ext.commands.bot" has no attribute "Bot"  [attr-defined]
- steam/ext/commands/cog.py:25: error: Cannot resolve name "UnboundListenerType" (possible cyclic definition)  [misc]
- steam/ext/commands/bot.py:49: error: Cannot resolve name "CommandPrefixType" (possible cyclic definition)  [misc]
- steam/ext/commands/bot.py:49: error: Cannot resolve name "Bot" (possible cyclic definition)  [misc]
- steam/ext/commands/bot.py:597: error: Unused "type: ignore" comment  [unused-ignore]
- steam/ext/commands/bot.py:599: error: Unused "type: ignore" comment  [unused-ignore]

Tanjun (https://github.com/FasterSpeeding/Tanjun)
- tanjun/hooks.py:191: error: Name "_MaybeAwaitable" is not defined  [name-defined]
- tanjun/hooks.py:207: error: Name "_MaybeAwaitable" is not defined  [name-defined]
- tanjun/hooks.py:221: error: Name "_MaybeAwaitable" is not defined  [name-defined]
- tanjun/components.py:147: error: Name "_MaybeAwaitable" is not defined  [name-defined]
- tanjun/commands/base.py:147: error: Name "_MaybeAwaitable" is not defined  [name-defined]
- tanjun/clients.py:147: error: Name "_MaybeAwaitable" is not defined  [name-defined]
All reactions

Sorry, something went wrong.

Uh oh!

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

@JukkaL JukkaL changed the title Fix various crahses on recursive type variable defaults Fix various crashes on recursive type variable defaults May 26, 2026
JukkaL
JukkaL approved these changes May 26, 2026
View reviewed changes

@JukkaL JukkaL left a comment

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.

Great to see multiple bugs fixed by one PR! Just one comment about a typo.

Sorry, something went wrong.

Uh oh!

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

All reactions
Comment thread mypy/semanal.py Outdated
# import foo.bar
self.transitive_submodule_imports: dict[str, set[str]] = {}

# Instances and type aliases that were fixed using default valuers of type

@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.

Typo: valuers

Sorry, something went wrong.

Uh oh!

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

All reactions
@ilevkivskyi
Fix typo
afc0cdc
@ilevkivskyi
ilevkivskyi merged commit 47ca4c2 into python:master May 26, 2026
@ilevkivskyi
ilevkivskyi deleted the fix-tv-default-crashes branch May 26, 2026 12:11
This was referenced Jun 23, 2026
2.2 release planning #21618
Closed
2.2 Regression with placeholder types in a TypeVar #21640
Closed
@delfick

delfick commented Jul 6, 2026

Copy link
Copy Markdown

@ilevkivskyi hello, this change seems to mean that in the release 2.2 branch my mypy plugin starts to be unable to resolve some placeholders #21640

All reactions

Sorry, something went wrong.

Uh oh!

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

netbsd-srcmastr pushed a commit to NetBSD/pkgsrc that referenced this pull request Jul 13, 2026
@0-wiz-0
py-mypy: update to 2.2.0.
687ff9c
## Mypy 2.2

### Support for Closed TypedDicts (PEP 728)

Mypy now supports closed TypedDicts as specified in PEP 728. A closed TypedDict cannot have extra
keys beyond those explicitly defined. This allows the type checker to determine that certain
operations are safe when they otherwise wouldn't be due to the potential presence of unknown keys.

You can use the `closed` keyword argument with `TypedDict`:

```python
HasName = TypedDict("HasName", {"name": str})
HasOnlyName = TypedDict("HasOnlyName", {"name": str}, closed=True)
Movie = TypedDict("Movie", {"name": str, "year": int})

movie: Movie = {"name": "Nimona", "year": 2023}
has_name: HasName = movie  # OK: HasName is open (default)
has_only_name: HasOnlyName = movie  # Error: HasOnlyName is closed and Movie has extra "year" key
```

Closed TypedDicts enable more precise type checking because the type checker knows exactly which
keys are present. This is particularly useful when working with TypedDict unions or when you want
to ensure that a TypedDict conforms to an exact shape.

The `closed` keyword also enables safe type narrowing with `in` checks:

```python
Book = TypedDict('Book', {'book': str}, closed=True)
DVD = TypedDict('DVD', {'dvd': str}, closed=True)
type Inventory = Book | DVD

def print_type(inventory: Inventory) -> None:
    if "book" in inventory:
        # Type is narrowed to Book here - safe because DVD is closed
        print(inventory["book"])
    else:
        # Type is narrowed to DVD here
        print(inventory["dvd"])
```

The `closed` keyword is also supported in class-based syntax:

```python
class HasOnlyName(TypedDict, closed=True):
    name: str
```

Note that closed TypedDicts are structural types, so a closed TypedDict is assignable to an open
TypedDict with the same keys, but not vice versa.

Contributed by Alice (PR [21382](python/mypy#21382)).

### Complete Support for Type Variable Defaults (PEP 696)

Mypy now has complete support for type variable defaults as specified in PEP 696. This allows you to
specify default values for type parameters in generic classes, functions, and type aliases.

Traditional syntax (Python 3.11 and earlier):

```python
T = TypeVar("T", default=int)  # This means that if no type is specified T = int

@DataClass
class Box(Generic[T]):
    value: T | None = None

reveal_type(Box())                      # type is Box[int]
reveal_type(Box(value="Hello World!"))  # type is Box[str]
```

New syntax (Python 3.12+):

```python
class Box[T = int]:
    def __init__(self, value: T) -> None:
        self.value = value

reveal_type(Box())                      # type is Box[int]
reveal_type(Box(value="Hello World!"))  # type is Box[str]
```

Type variable defaults work with all forms of generics, including classes, functions, and type aliases.
This release completes the implementation by fixing various edge cases involving recursive defaults,
dependencies between type variables, and interactions with variadic generics.

Contributed by Ivan Levkivskyi (PRs [21491](python/mypy#21491),
[21526](python/mypy#21526), [21544](python/mypy#21544)).

### Respect Explicit Return Type of `__new__()`

Mypy now respects explicitly annotated return types in `__new__()` methods. Previously, mypy would
always assume that `__new__()` returns an instance of the current class, ignoring explicit annotations.

With this change, if you explicitly annotate a return type that differs from the implicit type, mypy
will use the explicit annotation:

```python
class Factory:
    def __new__(cls) -> Product:
        return Product()

reveal_type(Factory())  # type is Product, not Factory
```

Note that mypy still gives an error at the definition site if the explicit annotation is not a
subtype of the current class, since this is technically not type-safe.

For backwards compatibility, there are two exceptions:
- If the return type is `Any`, mypy will still use the current class as the return type.
- If the explicit return type comes from a superclass and is a supertype of the implicit return type,
  mypy will use the implicit (more specific) type:

```python
class A:
    def __new__(cls) -> A: ...

reveal_type(A())  # type is A

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

class C(B): ...
reveal_type(C())  # type is C
```

This fixes several long-standing issues where explicit `__new__()` return types were ignored.

Contributed by Ivan Levkivskyi (PR [21441](python/mypy#21441)).

### TypeForm Support No Longer Experimental

Support for `TypeForm` is no longer experimental. `TypeForm` (introduced in Python 3.14) allows you
to annotate parameters that accept type expressions, providing better type checking for functions
that work with types as values.

```python
from typing import TypeForm

def make_list(tp: TypeForm[T]) -> list[T]:
    ...

# Correctly typed as list[int]
int_list = make_list(int)
```

`TypeForm` support was previously reverted from mypy 2.1 due to a performance regression, but this
has now been mitigated.

Contributed by Ivan Levkivskyi and Jelle Zijlstra (PRs [21262](python/mypy#21262), [21591](python/mypy#21591),
[21459](python/mypy#21459)).

### Experimental WASM Wheel for Python 3.14

Mypy now ships an experimental WebAssembly (WASM) wheel for Python 3.14. This allows mypy to run
in WASM environments such as Pyodide and browser-based Python implementations.

The WASM wheel is considered experimental and may have limitations compared to native builds. Please
report any issues you encounter when using mypy in WASM environments.

Contributed by Ivan Levkivskyi (PR [21671](python/mypy#21671)).

### Mypyc Free-threading Improvements

- Make function wrappers thread-safe on free-threaded builds (Jukka Lehtosalo, PR [21620](python/mypy#21620))
- Make list remove and index thread-safe on free-threaded builds (Jukka Lehtosalo, PR [21614](python/mypy#21614))
- Fix dict iteration memory safety on free-threaded builds (Jukka Lehtosalo, PR [21617](python/mypy#21617))
- Make some dict primitives thread-safe on free-threading builds (Jukka Lehtosalo, PR [21616](python/mypy#21616))
- Fix free-threading race condition in argument parsing (Jukka Lehtosalo, PR [21613](python/mypy#21613))
- Document free threading and other doc updates (Jukka Lehtosalo, PR [21494](python/mypy#21494))

### `librt.strings` Updates

- Add `librt.strings.toupper` and `librt.strings.tolower` codepoint primitives (Vaggelis Danias, PR [21553](python/mypy#21553))
- Add `librt.strings.isidentifier` codepoint primitive (Vaggelis Danias, PR [21522](python/mypy#21522))
- Add `librt.strings.isalpha` codepoint primitive (Vaggelis Danias, PR [21521](python/mypy#21521))
- Add `librt.strings.isalnum` codepoint primitive (Vaggelis Danias, PR [21509](python/mypy#21509))
- Add `librt.strings.isdigit` codepoint primitive (Vaggelis Danias, PR [21504](python/mypy#21504))
- Add `librt.strings.isspace` char primitive (Vaggelis Danias, PR [21462](python/mypy#21462))

### Mypyc Improvements

- Fix name lookup when class var and module var have the same name (Jukka Lehtosalo, PR [21594](python/mypy#21594))
- Report file and line number on uncaught exceptions (Jukka Lehtosalo, PR [21584](python/mypy#21584))
- Use `other` arg instead of `self` for RHS type (Ryan Heard, PR [21569](python/mypy#21569))
- Use `method_sig` to get the method signature (Ryan Heard, PR [21567](python/mypy#21567))
- Preserve inherited attribute defaults under `separate=True` (Jo, PR [21547](python/mypy#21547))
- Fix missing cross-group header deps in incremental builds (Jo, PR [21490](python/mypy#21490))
- Fix cross-group call to inherited `__mypyc_defaults_setup` (Jo, PR [21481](python/mypy#21481))
- Fix non-deterministic class struct layout under `separate=True` (Vaggelis Danias, PR [21530](python/mypy#21530))
- Specialize `s[i] == 'x'` to a codepoint int compare (Vaggelis Danias, PR [21579](python/mypy#21579))
- Fix reference leak in mypyc bytes concatenation (Colinxu2020, PR [21469](python/mypy#21469))

### Fixes to Crashes

- Fix crash on invalid recursive variadic alias (Ivan Levkivskyi, PR [21572](python/mypy#21572))
- Fix crashes on variadic unpacking in synthetic types (Ivan Levkivskyi, PR [21555](python/mypy#21555))
- Fix crash on unhandled meet variadic tuple vs instance (Ivan Levkivskyi, PR [21558](python/mypy#21558))
- Fix crash on deferred generic class nested in function (Ivan Levkivskyi, PR [21557](python/mypy#21557))
- Fix crash in new-style type alias with variadic unpack (Ivan Levkivskyi, PR [21551](python/mypy#21551))
- Fix various crashes on recursive type variable defaults (Ivan Levkivskyi, PR [21491](python/mypy#21491))
- Fix crash for empty `Annotated` type application (Rayan Salhab, PR [21503](python/mypy#21503))
- Fix crash on `Unpack` used without arguments in class bases (Sai Asish Y, PR [21470](python/mypy#21470))

### Performance Improvements

- Memoize the options snapshot (Kevin Kannammalil, PR [21354](python/mypy#21354))
- Don't include `not_ready_deps` tracking as relating to mypy internals (Kevin Kannammalil, PR [21389](python/mypy#21389))
- Speed up transitive dependency hash for singleton SCCs (Kevin Kannammalil, PR [21390](python/mypy#21390))
- Optimize typeform checks (Jelle Zijlstra, PR [21459](python/mypy#21459))

### Improvements to the Native Parser

- Support `--shadow-file` with `--native-parser` (Jukka Lehtosalo, PR [21623](python/mypy#21623))
- Add Python version checks to native parser (Kevin Kannammalil, PR [21539](python/mypy#21539))
- Allow nativeparse to parse source code directly (bzoracler, PR [21260](python/mypy#21260))

### Other Notable Fixes and Improvements

- Add function definition notes for `too many positional arguments` errors (Kevin Kannammalil, PR [21410](python/mypy#21410))
- Fix the exportjson tool (.ff cache to .json conversion) (Jukka Lehtosalo, PR [21628](python/mypy#21628))
- Support floats in JSON in fixed-format cache (Ivan Levkivskyi, PR [21603](python/mypy#21603))
- Update `TypedDictType.__init__` signature to preserve backward compat (Jukka Lehtosalo, PR [21590](python/mypy#21590))
- Fix constructor calls for union-bounded `TypeVar`s (Jingchen Ye, PR [21571](python/mypy#21571))
- Fix `TypedDict` indexing with literal keys in comprehensions (Jingchen Ye, PR [21556](python/mypy#21556))
- Correctly handle empty tuple index when unpacked (Ivan Levkivskyi, PR [21545](python/mypy#21545))
- Support protocol checks for self-types in tuple types (Ivan Levkivskyi, PR [21535](python/mypy#21535))
- Fix edge cases in variadic tuple subclasses (Ivan Levkivskyi, PR [21518](python/mypy#21518))
- Special-case constructor for tuple types (Ivan Levkivskyi, PR [21502](python/mypy#21502))
- Fix false positive "Expected TypedDict key to be string literal" for `Union[TypedDict, dict[K, V]]` (Zakir Jiwani, PR [21511](python/mypy#21511))
- Use explicit `Never` for type inference (Ivan Levkivskyi, PR [21497](python/mypy#21497))
- Narrow membership in statically known containers (Shantanu, PR [21461](python/mypy#21461))
- Improve negative narrowing for membership checks on tuples (Shantanu, PR [21456](python/mypy#21456))
- Analyze `TypedDict` decorators (Pranav Manglik, PR [21267](python/mypy#21267))
- Start testing Python 3.15 (Marc Mueller, PR [21439](python/mypy#21439))
- Improved handling of `NamedTuple`, `TypedDict`, `Enum`, and regular classes nested in functions (Ivan Levkivskyi, PR [21478](python/mypy#21478))
@luantaraschi luantaraschi mentioned this pull request Aug 20, 2026
Do not freeze an unresolved type variable default into an instance #21873
Closed
tsutsui pushed a commit to tsutsui/pkgsrc that referenced this pull request Oct 17, 2026
@0-wiz-0
py-mypy: update to 2.2.0.
4607693
## Mypy 2.2

### Support for Closed TypedDicts (PEP 728)

Mypy now supports closed TypedDicts as specified in PEP 728. A closed TypedDict cannot have extra
keys beyond those explicitly defined. This allows the type checker to determine that certain
operations are safe when they otherwise wouldn't be due to the potential presence of unknown keys.

You can use the `closed` keyword argument with `TypedDict`:

```python
HasName = TypedDict("HasName", {"name": str})
HasOnlyName = TypedDict("HasOnlyName", {"name": str}, closed=True)
Movie = TypedDict("Movie", {"name": str, "year": int})

movie: Movie = {"name": "Nimona", "year": 2023}
has_name: HasName = movie  # OK: HasName is open (default)
has_only_name: HasOnlyName = movie  # Error: HasOnlyName is closed and Movie has extra "year" key
```

Closed TypedDicts enable more precise type checking because the type checker knows exactly which
keys are present. This is particularly useful when working with TypedDict unions or when you want
to ensure that a TypedDict conforms to an exact shape.

The `closed` keyword also enables safe type narrowing with `in` checks:

```python
Book = TypedDict('Book', {'book': str}, closed=True)
DVD = TypedDict('DVD', {'dvd': str}, closed=True)
type Inventory = Book | DVD

def print_type(inventory: Inventory) -> None:
    if "book" in inventory:
        # Type is narrowed to Book here - safe because DVD is closed
        print(inventory["book"])
    else:
        # Type is narrowed to DVD here
        print(inventory["dvd"])
```

The `closed` keyword is also supported in class-based syntax:

```python
class HasOnlyName(TypedDict, closed=True):
    name: str
```

Note that closed TypedDicts are structural types, so a closed TypedDict is assignable to an open
TypedDict with the same keys, but not vice versa.

Contributed by Alice (PR [21382](python/mypy#21382)).

### Complete Support for Type Variable Defaults (PEP 696)

Mypy now has complete support for type variable defaults as specified in PEP 696. This allows you to
specify default values for type parameters in generic classes, functions, and type aliases.

Traditional syntax (Python 3.11 and earlier):

```python
T = TypeVar("T", default=int)  # This means that if no type is specified T = int

@DataClass
class Box(Generic[T]):
    value: T | None = None

reveal_type(Box())                      # type is Box[int]
reveal_type(Box(value="Hello World!"))  # type is Box[str]
```

New syntax (Python 3.12+):

```python
class Box[T = int]:
    def __init__(self, value: T) -> None:
        self.value = value

reveal_type(Box())                      # type is Box[int]
reveal_type(Box(value="Hello World!"))  # type is Box[str]
```

Type variable defaults work with all forms of generics, including classes, functions, and type aliases.
This release completes the implementation by fixing various edge cases involving recursive defaults,
dependencies between type variables, and interactions with variadic generics.

Contributed by Ivan Levkivskyi (PRs [21491](python/mypy#21491),
[21526](python/mypy#21526), [21544](python/mypy#21544)).

### Respect Explicit Return Type of `__new__()`

Mypy now respects explicitly annotated return types in `__new__()` methods. Previously, mypy would
always assume that `__new__()` returns an instance of the current class, ignoring explicit annotations.

With this change, if you explicitly annotate a return type that differs from the implicit type, mypy
will use the explicit annotation:

```python
class Factory:
    def __new__(cls) -> Product:
        return Product()

reveal_type(Factory())  # type is Product, not Factory
```

Note that mypy still gives an error at the definition site if the explicit annotation is not a
subtype of the current class, since this is technically not type-safe.

For backwards compatibility, there are two exceptions:
- If the return type is `Any`, mypy will still use the current class as the return type.
- If the explicit return type comes from a superclass and is a supertype of the implicit return type,
  mypy will use the implicit (more specific) type:

```python
class A:
    def __new__(cls) -> A: ...

reveal_type(A())  # type is A

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

class C(B): ...
reveal_type(C())  # type is C
```

This fixes several long-standing issues where explicit `__new__()` return types were ignored.

Contributed by Ivan Levkivskyi (PR [21441](python/mypy#21441)).

### TypeForm Support No Longer Experimental

Support for `TypeForm` is no longer experimental. `TypeForm` (introduced in Python 3.14) allows you
to annotate parameters that accept type expressions, providing better type checking for functions
that work with types as values.

```python
from typing import TypeForm

def make_list(tp: TypeForm[T]) -> list[T]:
    ...

# Correctly typed as list[int]
int_list = make_list(int)
```

`TypeForm` support was previously reverted from mypy 2.1 due to a performance regression, but this
has now been mitigated.

Contributed by Ivan Levkivskyi and Jelle Zijlstra (PRs [21262](python/mypy#21262), [21591](python/mypy#21591),
[21459](python/mypy#21459)).

### Experimental WASM Wheel for Python 3.14

Mypy now ships an experimental WebAssembly (WASM) wheel for Python 3.14. This allows mypy to run
in WASM environments such as Pyodide and browser-based Python implementations.

The WASM wheel is considered experimental and may have limitations compared to native builds. Please
report any issues you encounter when using mypy in WASM environments.

Contributed by Ivan Levkivskyi (PR [21671](python/mypy#21671)).

### Mypyc Free-threading Improvements

- Make function wrappers thread-safe on free-threaded builds (Jukka Lehtosalo, PR [21620](python/mypy#21620))
- Make list remove and index thread-safe on free-threaded builds (Jukka Lehtosalo, PR [21614](python/mypy#21614))
- Fix dict iteration memory safety on free-threaded builds (Jukka Lehtosalo, PR [21617](python/mypy#21617))
- Make some dict primitives thread-safe on free-threading builds (Jukka Lehtosalo, PR [21616](python/mypy#21616))
- Fix free-threading race condition in argument parsing (Jukka Lehtosalo, PR [21613](python/mypy#21613))
- Document free threading and other doc updates (Jukka Lehtosalo, PR [21494](python/mypy#21494))

### `librt.strings` Updates

- Add `librt.strings.toupper` and `librt.strings.tolower` codepoint primitives (Vaggelis Danias, PR [21553](python/mypy#21553))
- Add `librt.strings.isidentifier` codepoint primitive (Vaggelis Danias, PR [21522](python/mypy#21522))
- Add `librt.strings.isalpha` codepoint primitive (Vaggelis Danias, PR [21521](python/mypy#21521))
- Add `librt.strings.isalnum` codepoint primitive (Vaggelis Danias, PR [21509](python/mypy#21509))
- Add `librt.strings.isdigit` codepoint primitive (Vaggelis Danias, PR [21504](python/mypy#21504))
- Add `librt.strings.isspace` char primitive (Vaggelis Danias, PR [21462](python/mypy#21462))

### Mypyc Improvements

- Fix name lookup when class var and module var have the same name (Jukka Lehtosalo, PR [21594](python/mypy#21594))
- Report file and line number on uncaught exceptions (Jukka Lehtosalo, PR [21584](python/mypy#21584))
- Use `other` arg instead of `self` for RHS type (Ryan Heard, PR [21569](python/mypy#21569))
- Use `method_sig` to get the method signature (Ryan Heard, PR [21567](python/mypy#21567))
- Preserve inherited attribute defaults under `separate=True` (Jo, PR [21547](python/mypy#21547))
- Fix missing cross-group header deps in incremental builds (Jo, PR [21490](python/mypy#21490))
- Fix cross-group call to inherited `__mypyc_defaults_setup` (Jo, PR [21481](python/mypy#21481))
- Fix non-deterministic class struct layout under `separate=True` (Vaggelis Danias, PR [21530](python/mypy#21530))
- Specialize `s[i] == 'x'` to a codepoint int compare (Vaggelis Danias, PR [21579](python/mypy#21579))
- Fix reference leak in mypyc bytes concatenation (Colinxu2020, PR [21469](python/mypy#21469))

### Fixes to Crashes

- Fix crash on invalid recursive variadic alias (Ivan Levkivskyi, PR [21572](python/mypy#21572))
- Fix crashes on variadic unpacking in synthetic types (Ivan Levkivskyi, PR [21555](python/mypy#21555))
- Fix crash on unhandled meet variadic tuple vs instance (Ivan Levkivskyi, PR [21558](python/mypy#21558))
- Fix crash on deferred generic class nested in function (Ivan Levkivskyi, PR [21557](python/mypy#21557))
- Fix crash in new-style type alias with variadic unpack (Ivan Levkivskyi, PR [21551](python/mypy#21551))
- Fix various crashes on recursive type variable defaults (Ivan Levkivskyi, PR [21491](python/mypy#21491))
- Fix crash for empty `Annotated` type application (Rayan Salhab, PR [21503](python/mypy#21503))
- Fix crash on `Unpack` used without arguments in class bases (Sai Asish Y, PR [21470](python/mypy#21470))

### Performance Improvements

- Memoize the options snapshot (Kevin Kannammalil, PR [21354](python/mypy#21354))
- Don't include `not_ready_deps` tracking as relating to mypy internals (Kevin Kannammalil, PR [21389](python/mypy#21389))
- Speed up transitive dependency hash for singleton SCCs (Kevin Kannammalil, PR [21390](python/mypy#21390))
- Optimize typeform checks (Jelle Zijlstra, PR [21459](python/mypy#21459))

### Improvements to the Native Parser

- Support `--shadow-file` with `--native-parser` (Jukka Lehtosalo, PR [21623](python/mypy#21623))
- Add Python version checks to native parser (Kevin Kannammalil, PR [21539](python/mypy#21539))
- Allow nativeparse to parse source code directly (bzoracler, PR [21260](python/mypy#21260))

### Other Notable Fixes and Improvements

- Add function definition notes for `too many positional arguments` errors (Kevin Kannammalil, PR [21410](python/mypy#21410))
- Fix the exportjson tool (.ff cache to .json conversion) (Jukka Lehtosalo, PR [21628](python/mypy#21628))
- Support floats in JSON in fixed-format cache (Ivan Levkivskyi, PR [21603](python/mypy#21603))
- Update `TypedDictType.__init__` signature to preserve backward compat (Jukka Lehtosalo, PR [21590](python/mypy#21590))
- Fix constructor calls for union-bounded `TypeVar`s (Jingchen Ye, PR [21571](python/mypy#21571))
- Fix `TypedDict` indexing with literal keys in comprehensions (Jingchen Ye, PR [21556](python/mypy#21556))
- Correctly handle empty tuple index when unpacked (Ivan Levkivskyi, PR [21545](python/mypy#21545))
- Support protocol checks for self-types in tuple types (Ivan Levkivskyi, PR [21535](python/mypy#21535))
- Fix edge cases in variadic tuple subclasses (Ivan Levkivskyi, PR [21518](python/mypy#21518))
- Special-case constructor for tuple types (Ivan Levkivskyi, PR [21502](python/mypy#21502))
- Fix false positive "Expected TypedDict key to be string literal" for `Union[TypedDict, dict[K, V]]` (Zakir Jiwani, PR [21511](python/mypy#21511))
- Use explicit `Never` for type inference (Ivan Levkivskyi, PR [21497](python/mypy#21497))
- Narrow membership in statically known containers (Shantanu, PR [21461](python/mypy#21461))
- Improve negative narrowing for membership checks on tuples (Shantanu, PR [21456](python/mypy#21456))
- Analyze `TypedDict` decorators (Pranav Manglik, PR [21267](python/mypy#21267))
- Start testing Python 3.15 (Marc Mueller, PR [21439](python/mypy#21439))
- Improved handling of `NamedTuple`, `TypedDict`, `Enum`, and regular classes nested in functions (Ivan Levkivskyi, PR [21478](python/mypy#21478))
@Choco-princess Choco-princess mentioned this pull request Nov 1, 2026
Segfault on class parameterised by a TypeVar whose default is itself (TypeVar("T", default="T")) #22344
Open
@d-v-b d-v-b mentioned this pull request Nov 14, 2026
fix(deps): support pydantic-zarr 0.11 and require >= 0.10 d-v-b/ome-zarr-models-py#1
Open
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@JukkaL JukkaL JukkaL approved these changes
@hauntsaninja hauntsaninja Awaiting requested review from hauntsaninja
@cdce8p cdce8p Awaiting requested review from cdce8p

Uh oh!

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

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Crash with recursive default type parameter Crash on type alias bounded by and defaulted to itself Cyclic definition error when defaulting TypeVar on base class to subclass AssertionError: Must not defer during final iteration

Uh oh!

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

3 participants

@ilevkivskyi @delfick @JukkaL
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 01402775 — 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.