ensure that both __exit__ and __enter__ are defined

This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

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: Cyril-Bouchiat/add-vm-package-explorer-doc