contextmanager

Why doesn't the MySQLdb Connection context manager close the cursor?

两盒软妹~` 提交于 2019-12-03 09:57:22
MySQLdb Connections have a rudimentary context manager that creates a cursor on enter , either rolls back or commits on exit , and implicitly doesn't suppress exceptions. From the Connection source : def __enter__(self): if self.get_autocommit(): self.query("BEGIN") return self.cursor() def __exit__(self, exc, value, tb): if exc: self.rollback() else: self.commit() So, does anyone know why the cursor isn't closed on exit? At first, I assumed it was because closing the cursor didn't do anything and that cursors only had a close method in deference to the Python DB API (see the comments to this

How to manipulate the exception in __exit__ of a context manager?

为君一笑 提交于 2019-12-03 08:23:09
I know it's bad style to re-raise an exception from within a context manager's __exit__() method. So, I'd like to tack an attribute on the instance which can carry contextual information that isn't available if I let the exception trickle through or if I catch it. This will avoid re-raising it. The alternative to tacking the attribute on the exception would be to swallow the exception, set some state on the instance that doubles as the context manager in question and later check that state. Problem is that this would lead to a catch 22, wouldn't it? Since the exception means that execution

python 'with' statement, should I use contextlib.closing?

喜欢而已 提交于 2019-12-03 05:14:57
from contextlib import closing def init_db(): with closing(connect_db()) as db: with app.open_resource('schema.sql') as f: db.cursor().executescript(f.read()) db.commit() This is from flask tutorial Step 3( http://flask.pocoo.org/docs/tutorial/dbinit/#tutorial-dbinit ). And I'm little curious about the line 4 of that. Must I import and use that 'contextlib.closing()' method? When I've learned about with statement, many articles said that it closes file automatically after process like below.(same as Finally: thing.close()) with open('filename','w') as f: f.write(someString); Even though I don

Function acting as both decorator and context manager in Python?

我只是一个虾纸丫 提交于 2019-12-03 01:28:42
问题 This might be pushing things a little too far, but mostly out of curiosity.. Would it be possible to have a callable object (function/class) that acts as both a Context Manager and a decorator at the same time: def xxx(*args, **kw): # or as a class @xxx(foo, bar) def im_decorated(a, b): print('do the stuff') with xxx(foo, bar): print('do the stuff') 回答1: Starting in Python 3.2, support for this is even included in the standard library. Deriving from the class contextlib.ContextDecorator makes

Finding Functions Defined in a with: Block

假如想象 提交于 2019-12-02 18:30:32
Here's some code from Richard Jones' Blog : with gui.vertical: text = gui.label('hello!') items = gui.selection(['one', 'two', 'three']) with gui.button('click me!'): def on_click(): text.value = items.value text.foreground = red My question is: how the heck did he do this? How can the context manager access the scope inside the with block? Here's a basic template for trying to figure this out: from __future__ import with_statement class button(object): def __enter__(self): #do some setup pass def __exit__(self, exc_type, exc_value, traceback): #XXX: how can we find the testing() function?

StringIO and compatibility with 'with' statement (context manager)

醉酒当歌 提交于 2019-12-02 17:00:07
I have some legacy code with a legacy function that takes a filename as an argument and processes the file contents. A working facsimile of the code is below. What I want to do is not have to write to disk with some content that I generate in order to use this legacy function, so I though I could use StringIO to create an object in place of the physical filename. However, this does not work, as you can see below. I thought StringIO was the way to go with this. Can anyone tell me if there is a way to use this legacy function and pass it something in the argument that isn't a file on disk but

Function acting as both decorator and context manager in Python?

孤街浪徒 提交于 2019-12-02 16:42:57
This might be pushing things a little too far, but mostly out of curiosity.. Would it be possible to have a callable object (function/class) that acts as both a Context Manager and a decorator at the same time: def xxx(*args, **kw): # or as a class @xxx(foo, bar) def im_decorated(a, b): print('do the stuff') with xxx(foo, bar): print('do the stuff') 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

Is it possible to access the context object (code block) inside the __exit__() method of a context manager?

偶尔善良 提交于 2019-12-02 00:05:25
问题 I would like to invoke the code object again in the exit () method if it raises an exception (maybe several times, maybe with delay). I know it is very easy to do with a decorator, but my motivation is that sometimes I want to repeat just some fragment of code that I don't want to extract to a separate function and decorate it. I'm looking for something along these lines: class again(object): def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is not None: ???

Is it wise to use with with statements in generators?

a 夏天 提交于 2019-12-01 19:01:05
Consider the following Python code: def values(): with somecontext(): yield 1 yield 2 for v in values(): print(v) break In this case, does Python guarantee that the generator is properly closed and, thus, that the context is exited? I realize that it, in practice, is going to be the case in CPython due to reference counting and eager destruction of the generator, but does Python guarantee this behavior? I do notice that it does indeed not work in Jython, so should that be considered a bug or allowable behavior? Yes, you can use a with statement in a generator without issue. Python will handle

Why does my contextmanager-function not work like my contextmanager class in python?

╄→尐↘猪︶ㄣ 提交于 2019-12-01 07:36:21
In my code, I need to be able to open and close a device properly, and therefore see the need to use a context manager. While a context manager is usually defined as a class with __enter__ and __exit__ methods, there also seem to be the possibility to decorate a function for use with the context manager (see a recent post and another nice example here ). In the following (working) code snippet, I have implemented the two possibilities; one just need to swap the commented line with the other one: import time import contextlib def device(): return 42 @contextlib.contextmanager def wrap(): print(