Skip to content

Fix sentinel identity loss through generic substitution and inference - #21888

Open
edgarrmondragon wants to merge 1 commit into
python:masterfrom
edgarrmondragon:sentinel-typevar-expand
Open

Fix sentinel identity loss through generic substitution and inference#21888
edgarrmondragon wants to merge 1 commit into
python:masterfrom
edgarrmondragon:sentinel-typevar-expand

Conversation

@edgarrmondragon

@edgarrmondragon edgarrmondragon commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

A sentinel's only way to identify itself is via its attached literal value, unlike e.g. enum members whose class already carries identity. That literal was being unconditionally stripped both when a TypeVar was substituted with a sentinel instance (e.g. dict.get's overloaded default parameter) and when inferring the type of a plain variable assignment, collapsing every sentinel down to the same uninformative sentinel type. Preserve it in both cases.

Fixes #21866
Follow-up from #21647

A sentinel's only way to identify itself is via its attached literal
value, unlike e.g. enum members whose class already carries identity.
That literal was being unconditionally stripped both when a TypeVar
was substituted with a sentinel instance (e.g. `dict.get`'s overloaded
default parameter) and when inferring the type of a plain variable
assignment, collapsing every sentinel down to the same uninformative
`sentinel` type. Preserve it in both cases.

Fixes python#21866
Follow-up from python#21647

Signed-off-by: Edgar Ramírez Mondragón <edgarrm358@gmail.com>

assert_type(ALIAS, sentinel)
# The value still identifies as the same sentinel...
assert_type(ALIAS, MISSING)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think this is more useful now and still in line with #21647 (comment) and the spec:

https://typing.python.org/en/latest/spec/special-types.html#sentinels

@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@edgarrmondragon
edgarrmondragon marked this pull request as ready for review August 24, 2026 19:19

@cdce8p cdce8p left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for looking into it @edgarrmondragon! The changes make sense and look good to me.

@cdce8p
cdce8p requested a review from JelleZijlstra August 24, 2026 21:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Invalid return type with sentinel and dict.get

2 participants