Skip to content

Warn if __exit__ doesn't have the right signature. #4885

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
JelleZijlstra opened this issue Apr 11, 2018 · 2 comments
Open

Warn if __exit__ doesn't have the right signature. #4885

JelleZijlstra opened this issue Apr 11, 2018 · 2 comments

Comments

@JelleZijlstra
Copy link
Member

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.

@gvanrossum
Copy link
Member

gvanrossum commented Apr 12, 2018 via email

@AlexWaygood
Copy link
Member

AlexWaygood commented Apr 3, 2022

We actually just implemented this in flake8-pyi (a flake8 plugin for linting stub files, which typeshed uses in its CI): PyCQA/flake8-pyi#199

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants