Skip to content

Nice to have: context managers #2601

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
johnkntran opened this issue Apr 29, 2025 · 1 comment
Closed

Nice to have: context managers #2601

johnkntran opened this issue Apr 29, 2025 · 1 comment

Comments

@johnkntran
Copy link

johnkntran commented Apr 29, 2025

Would be nice to be able to use a with statement to close the connections:

with KafkaProducer(...) as producer:
    producer.send(...)

Instead of try/finally:

producer = KafkaProducer(...)
try:
    producer.send(...)
finally:
    producer.close()

Just add this code to KafkaProducer, KafkaConsumer, KafkaClient, KafkaAdminClient:

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.close()

I tried to push a PR for you to save the trouble, but was denied.

Image

@dpkp
Copy link
Owner

dpkp commented Apr 29, 2025

protip:

from contextlib import closing

with closing(KafkaProducer(...)) as producer:
    producer.send(...)

@dpkp dpkp closed this as completed Apr 29, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants