Skip to content

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

@JelleZijlstra

Description

@JelleZijlstra

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.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions