Skip to content

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.  #17086

Open
@wyattscarpenter

Description

@wyattscarpenter

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:

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions