contextmanager

Conditional or optional context managers in with statement

一个人想着一个人 提交于 2019-12-05 09:35:32
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 code which are exactly identical, is there a cleaner way of writing this? I'm aware that I could write

Writing a Python class that can only be used as a context manager [duplicate]

馋奶兔 提交于 2019-12-05 05:44:50
This question already has an answer here: How to check if an object is created with `with` statement? 5 answers Is there a way in Python to write a class that will error unless it's used with a with statement? # Okay: with Foo() as f1: f1.func1() f1.func2() # Not okay: f2 = Foo() f2.func1() I can do it manually: have __enter__ set a flag and have every other method check for that flag. But is there a nicer way to do it? Here's code for the not-so-since way: class Foo(object): def __init__(self): self._entered = False def __enter__(self): self._entered = True return self def _verify_entered

How do I make a contextmanager with a loop inside?

我只是一个虾纸丫 提交于 2019-12-05 01:34:56
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 equipment. It's obviously a full Python REPL, but most of the time the user is just calling predefined

Context Manager Hackery

浪子不回头ぞ 提交于 2019-12-04 16:36:45
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 SkippableContext(object): def __init__(self,mode=0): """ if mode = 0, proceed as normal if mode = 1,

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

两盒软妹~` 提交于 2019-12-04 15:54:28
问题 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

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

浪尽此生 提交于 2019-12-04 11:35:45
问题 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.

Is it wise to use with with statements in generators?

扶醉桌前 提交于 2019-12-04 03:56:30
问题 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

Python timeout context manager with threads

落花浮王杯 提交于 2019-12-03 12:38:40
I have timeout context manager that works perfectly with signals but it raises error in multithread mode because signals work only in main thread. def timeout_handler(signum, frame): raise TimeoutException() @contextmanager def timeout(seconds): old_handler = signal.signal(signal.SIGALRM, timeout_handler) signal.alarm(seconds) try: yield finally: signal.alarm(0) signal.signal(signal.SIGALRM, old_handler) I've seen decorator implementation of timeout but I don't know how to pass yield inside class derived from threading.Thread . My variant won't work. @contextmanager def timelimit(seconds):

Is it good practice to depend on python's with…as statement

拈花ヽ惹草 提交于 2019-12-03 11:52:40
问题 I'm curious if it is considered safe or good practice to depend on python's with...as statement. For example when opening a file: with open("myfile","w") as myFile: #do something So in this example I neglected to explicitly call myFile.close() however I can assume it was called when python exited the with...as statement by calling the objects __exit__() method. Is it good practice/safe to depend upon this or would it be better to always explicitly call file.close() 回答1: This is what context

what does yield without value do in context manager

时光总嘲笑我的痴心妄想 提交于 2019-12-03 11:09:27
import contextlib import time @contextlib.contextmanager def time_print(task_name): t = time.time() try: yield finally: print task_name, "took", time.time() - t, "seconds." def doproc(): x=1+1 with time_print("processes"): [doproc() for _ in range(500)] # processes took 15.236166954 seconds. when does doproc get executed when using this decorator? yield expression returns control to the whatever is using the generator. The generator pauses at this point, which means that the @contextmanager decorator knows that the code is done with the setup part. In other words, everything you want to do in