ensure that both __exit__ and __enter__ are defined

このページは日本語には対応しておりません。随時翻訳に取り組んでいます。翻訳に関してご質問やご意見ございましたら、お気軽にご連絡ください。

Metadata

ID: python-best-practices/ctx-manager-enter-exit-defined

Language: Python

Severity: Error

Category: Best Practices

Description

Methods __enter__ and __exit__ must be declared together. If one method is missing, we should make sure both are defined.

Learn More

Non-Compliant Code Examples

class Ctx:
    def __exit__(self, *exc):  # the method __enter__ should be defined.
        pass
class Ctx:
    def __enter__(self):  # the method __exit__ should also be defined.
        pass

Compliant Code Examples

class Ctx:
    def __enter__(self):
        pass
    def __exit__(self, *exc):
        pass
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis

PREVIEWING: may/unit-testing