contextmanager

python how to safely handle an exception inside a context manager

心不动则不痛 提交于 2019-12-09 14:19:43
问题 I think I've read that exceptions inside a with do not allow __exit__ to be call correctly. If I am wrong on this note, pardon my ignorance. So I have some pseudo code here, my goal is to use a lock context that upon __enter__ logs a start datetime and returns a lock id, and upon __exit__ records an end datetime and releases the lock: def main(): raise Exception with cron.lock() as lockid: print('Got lock: %i' % lockid) main() How can I still raise errors in addition to existing the context

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

我与影子孤独终老i 提交于 2019-12-09 05:09:06
问题 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.

Where is a Python built-in object's __enter__() and __exit__() defined?

旧巷老猫 提交于 2019-12-07 12:11:02
问题 I've read that the object's __ enter__() and __ exit__() methods are called every time 'with' is used. I understand that for user-defined objects, you can define those methods yourself, but I don't understand how this works for built-in objects/functions like 'open' or even the testcases. This code works as expected and I assume it closes the file with __ exit__(): with open('output.txt', 'w') as f: f.write('Hi there!') or with self.assertRaises(ValueError): remove_driver(self.driver) # self

Other builtin or practical examples of python `with` statement usage?

旧巷老猫 提交于 2019-12-07 08:15:17
问题 Does anyone have a real world example outside of python's file object implementation of an __enter__ and __exit__ use case? Preferably your own, since what I'm trying to achieve is a better way to conceptualize the cases where it would be used. I've already read this. And, here's a link to the python documentation. 回答1: There are many uses. Just in the standard library we have: sqlite3 ; using the connection as a context manager translates to committing or aborting the transaction. unittest ;

Conditional or optional context managers in with statement

一世执手 提交于 2019-12-07 06:10:46
问题 Suppose I have some kind of context manager (from a third-party library) that I am using like so: with freeze_time(test_dt): lines_of_code_1 lines_of_code_2 lines_of_code_3 But, suppose if there is no value for test_dt, the context manager should not run, but all of the remaining code should run, like so: if test_dt: with freeze_time(test_dt): lines_of_code_1 lines_of_code_2 lines_of_code_3 else: lines_of_code_1 lines_of_code_2 lines_of_code_3 Assume that lines_of_code here is 2-3 lines of

How do I make a contextmanager with a loop inside?

梦想的初衷 提交于 2019-12-06 20:49:15
问题 I want something like this: from contextlib import contextmanager @contextmanager def loop(seq): for i in seq: try: do_setup(i) yield # with body executes here do_cleanup(i) except CustomError as e: print(e) with loop([1,2,3]): do_something_else() do_whatever() But contextmanager doesn't work because it expects the generator to yield exactly once. The reason why I want this is because I basically want to make my own custom for loop. I have a modified IPython that is used to control test

why does Contextmanager throws a runtime error 'generator didn't stop after throw()'?

一世执手 提交于 2019-12-06 19:01:10
问题 In my utility.py I have, @contextmanager def rate_limit_protection(max_tries=3, wait=300): tries = 0 while max_tries > tries: try: yield break except FacebookRequestError as e: pprint.pprint(e) if e._body['error']['message'] == '(#17) User request limit reached': print("waiting...") time.sleep(wait) tries += 1 In my task.py I call: for date in interval: with utility.rate_limit_protection(): stats = account.get_insights(params=params) After runing the task for a given date range, once Facebook

Context Managers in Matlab: Invoking __enter__ in Matlab

僤鯓⒐⒋嵵緔 提交于 2019-12-06 13:41:45
I have a python package and I would like to use its classes and methods in Matlab. I know that this can be done directly since Matlab 2014b. I mean all you have to do is add py. in the beginning of your statements. So far so good, however, I couldn't figure out how to deal with context managers through MATLAB, which are invoked using the with statement. For instance, assume that we have the following class in a module called app.py, class App(object): def __init__(self, input): self._input = input self._is_open = False def __enter__(self): self._is_open = True # many other stuff going after

Context Manager Hackery

喜你入骨 提交于 2019-12-06 11:56:59
问题 I'm trying to make a quick and dirty caching system for Python, using the trick that a context-manager can be made to conditionally skip the code in its context — see Skipping execution of -with- block. I've stumbled upon a weird failure case of this and I was wondering if someone can help understand and fix this. Before anyone says this, I know what I'm doing is terrible and I shouldn't do it, etc, etc. Anyway, here is the code for the tricky context manager: import sys import inspect class

Other builtin or practical examples of python `with` statement usage?

给你一囗甜甜゛ 提交于 2019-12-05 15:30:28
Does anyone have a real world example outside of python's file object implementation of an __enter__ and __exit__ use case? Preferably your own, since what I'm trying to achieve is a better way to conceptualize the cases where it would be used. I've already read this . And, here's a link to the python documentation. There are many uses. Just in the standard library we have: sqlite3 ; using the connection as a context manager translates to committing or aborting the transaction. unittest ; using assertRaises as a context manager lets you assert an exception is raised, then test aspects of the