Warn if `__exit__` doesn't have the right signature.

Open
#4,885 2 comments 9 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
38/100
Issue type
Feature
Clarity
Clearly specified
Activity status
Stale
Tech stack
python
Domain
devtools

Research direction

Start by tracing mypy's existing checks for binary operators and its handling of the ContextManager protocol. Compare those entry points with the standard exit signature shown in the issue; done means incompatible exit methods produce a warning without rejecting compatible implementations.

Written by the indexing model from the issue text.

Description

feature needs discussion priority-2-low

A typeshed user found that zipfile.ZipFile wasn't compatible with the ContextManager protocol, and it turns out that this was because its __exit__ method was declared as taking Exception instead of BaseException: python/typeshed#2043.

I imagine this kind of mistake is pretty common in user code, and it won't be noticed until somebody tries to pass the object to an API that accepts a ContextManager and the user gets an obscure error. Perhaps mypy should warn for __exit__ methods that are not compatible with the standard signature:

    def __exit__(self, t: Optional[Type[BaseException]] = ..., value: Optional[BaseException] = ...,
                 traceback: Optional[TracebackType] = ...) -> bool: ...

Doing this makes more sense for __exit__ than for many other special methods because __exit__'s signature is rather more complicated than that of other dunders, so it's easier to make mistakes. mypy already does something similar for binary operators.

Dominant language
Python
Stars
20.6k
Forks
3.3k
Avg merge
1d 18h
Merged PRs (30d)
54

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.

More from python/mypy

All issues in python/mypy

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.