ensure that both __exit__ and __enter__ are defined

Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.

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