Skip to content

Fix narrowing with chained comparison#21150

Open
hauntsaninja wants to merge 1 commit intopython:masterfrom
hauntsaninja:chainnarrow
Open

Fix narrowing with chained comparison#21150
hauntsaninja wants to merge 1 commit intopython:masterfrom
hauntsaninja:chainnarrow

Conversation

@hauntsaninja
Copy link
Copy Markdown
Collaborator

Fixes #21149 (the regression part of it, still working on the bad behaviour present in previous mypy versions)

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 2, 2026

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

def f1(a: str | None, b: str | None) -> None:
if None is not a == b:
reveal_type(a) # N: Revealed type is "builtins.str"
reveal_type(b) # N: Revealed type is "builtins.str | None"
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

This should also be str. I will fix this in a subsequent PR (this one is not a regression, it will need net new code)

# TODO: support regular and len() narrowing in the same chain.
if any(m != ({}, {}) for m in partial_type_maps):
return reduce_conditional_maps(partial_type_maps)
if any(len(m[0]) or len(m[1]) for m in partial_type_maps):
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

TBH I don't understand how is this different from what it was before. Is this just some drive-by performance micro-optimization?

if any(m != ({}, {}) for m in partial_type_maps):
return reduce_conditional_maps(partial_type_maps)
if any(len(m[0]) or len(m[1]) for m in partial_type_maps):
return reduce_conditional_maps(partial_type_maps, use_meet=True)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I am in favour of this, but just as a warning, this may have some subtle side-effect w.r.t. Any, so you may want to add some tests involving Any as well.

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.

[1.20 regression] loss of type inference of chained-comparison operands

2 participants