python / python/mypy

When a type error results from type information being lost because an object (context manager) is used with `with` (with-as block), mypy should emit a hint alluding to this.

Open
#17,086 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

feature
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Feature

When a type error results from type information being lost because an object (context manager) is used with with (with-as block), mypy should emit a hint alluding to this.

Pitch

Consider the following issue, which is not by me but is a predicament I also ran into recently:

https://github.com/python/mypy/issues/9750

The user is, essentially, confused why the type of x.y is int but the type of c.y in with x as c: c.y is Any.

This happens because the __enter__ method of x is missing a return type signature, so mypy treats its output as having type Any. However, it is a common (as fair as I can tell) pattern for an object's __enter__ method to simply return self — possibly without a proper type signature, thus wiping its type information in the process. So, I think this would be a useful hint for mypy to emit, if it encounters any type problems where the problematic value has just resulted from a with statement.

Something like: hint: the type of c.y is Any, but the type of x is Foo. Did you mean the type of c to be Foo? If so, add the return type annotation -> Self to the __enter__ method of Foo.

Currently, there is no warning about this whatsoever, which means in the (admittedly, rare) circumstances where this problem crops up, it is unintuitive and the user has very little to go off of.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the context-manager case described in issue #9750, focusing on a missing return annotation on enter and the resulting Any type. Trace how mypy handles with-as expressions and type errors, then define the diagnostic's expected hint and tests for cases where the context manager returns itself.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.