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