mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Re-widen custom properties after narrowing

Open ilevkivskyi opened this issue 7 months ago • 2 comments

Fixes https://github.com/python/mypy/issues/10399

This is another smaller cleanup for https://github.com/python/mypy/issues/7724. The current logic as documented is IMO correct, for attributes (either properties or custom descriptors) with setter type different from getter type, we narrow the attribute type in an assignment if:

  • The attribute is "normalizing", i.e. getter type is a subtype of setter type (e.g. Sequence[Employee] is normalized to tuple[Employee, ...])
  • The given r.h.s. type in the assignment is a subtype of getter type (and thus transitively the setter as well), e.g. tuple[Manager, ...] vs tuple[Employee, ...] in the example above.

The problem was that this logic was implemented too literally, as a result assignments that didn't satisfy these two rules were simply ignored (thus making previous narrowing incorrectly "sticky"). In fact, we also need to re-widen previously narrowed types whenever second condition is not satisfied.

(I also decided to rename one variable name to make it more obvious.)

ilevkivskyi avatar Jun 14 '25 11:06 ilevkivskyi

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

github-actions[bot] avatar Jun 14 '25 12:06 github-actions[bot]

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

github-actions[bot] avatar Jun 18 '25 20:06 github-actions[bot]