Asynchronous context manager

Since Python 3.7, you can write: from contextlib import asynccontextmanager @asynccontextmanager async def smtp_connection(): client = SMTPAsync() … try: await client.connect(smtp_url, smtp_port) await client.starttls() await client.login(smtp_username, smtp_password) yield client finally: await client.quit() Before 3.7, you can use the async_generator package for this. On 3.6, you can write: # This import changed, everything else is the … Read more

In python, is there a good idiom for using context managers in setup/teardown

How about overriding unittest.TestCase.run() as illustrated below? This approach doesn’t require calling any private methods or doing something to every method, which is what the questioner wanted. from contextlib import contextmanager import unittest @contextmanager def resource_manager(): yield ‘foo’ class MyTest(unittest.TestCase): def run(self, result=None): with resource_manager() as resource: self.resource = resource super(MyTest, self).run(result) def test(self): self.assertEqual(‘foo’, … Read more

Function acting as both decorator and context manager in Python?

Starting in Python 3.2, support for this is even included in the standard library. Deriving from the class contextlib.ContextDecorator makes it easy to write classes that can be used as both, a decorator or a context manager. This functionality could be easily backported to Python 2.x — here is a basic implementation: class ContextDecorator(object): def … Read more

How do I write a null (no-op) contextmanager in Python?

Python 3.7 and above: use contextlib.nullcontext, specifically designed for this reason. Before Python 3.7, the standard library does not offer a context manager specifically designed for these use cases, but there are some workarounds. Since Python 3.4, contextlib.suppress can be used for that purpose in the first case, i.e. when there is no as clause: … Read more

Explaining Python’s ‘__enter__’ and ‘__exit__’

Using these magic methods (__enter__, __exit__) allows you to implement objects which can be used easily with the with statement. The idea is that it makes it easy to build code which needs some ‘cleandown’ code executed (think of it as a try-finally block). Some more explanation here. A useful example could be a database … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)