Is it safe to combine ‘with’ and ‘yield’ in python?

You bring up a criticism that has been raised before1. The cleanup in this case is non-deterministic, but it will happen with CPython when the generator gets garbage collected. Your mileage may vary for other python implementations… Here’s a quick example: from __future__ import print_function import contextlib @contextlib.contextmanager def manager(): “””Easiest way to get a … Read more

tempfile.TemporaryDirectory context manager in Python 2.7

Another option is the “backports.tempfile” package on pypi: https://pypi.python.org/pypi/backports.tempfile Quoting the project’s description: “This package provides backports of new features in Python’s tempfile module under the backports namespace.” Install with: pip install backports.tempfile Then use it in your script: from backports import tempfile with tempfile.TemporaryDirectory() as temp_dir: # modify files in this dir # here … Read more

Invoking a constructor in a ‘with’ statement

The __enter__ method should return the context object. with … as … uses the return value of __enter__ to determine what object to give you. Since your __enter__ returns nothing, it implicitly returns None, so test is None. with Test(‘first’) as test: print(f’in {test.name}’) test = Test(‘second’) with test: print(f’in {test.name}’) So test is none. … Read more

pass argument to __enter__

Yes, you can get the effect by adding a little more code. #!/usr/bin/env python class Clippy_Runner( dict ): def __init__( self ): pass def __call__( self, **kwargs ): self.update( kwargs ) return self def __enter__( self ): return self def __exit__( self, exc_type, exc_val, exc_tb ): self.clear() clippy_runner = Clippy_Runner() print clippy_runner.get(‘verbose’) # Outputs None … Read more

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