contextmanager

Combine two context managers into one

為{幸葍}努か 提交于 2019-11-29 03:11:38
I use Python 2.7 and I know that I can write this: with A() as a, B() as b: do_something() I want to provide a convenience helper which does both. The usage of this helper should look like this: with AB() as ab: do_something() Now AB() should do both: Create context A() and create context B(). I have no clue how to write this convenience helper Don't re-invent the wheel; this is not as simple as it looks. Context managers are treated as a stack , and should be exited in reverse order in which they are entered, for example. If an exception occurred, this order matters , as any context manager

Is Python *with* statement exactly equivalent to a try - (except) - finally block?

邮差的信 提交于 2019-11-29 02:15:06
问题 I know this was widely discussed, but I still can't find an answer to confirm this: is the with statement identical to calling the same code in a try - (except) -finally block, where whatever one defines in the __exit__ function of the context manager is placed in the finally block? For example -- are these 2 code snippets doing exactly the same thing? import sys from contextlib import contextmanager @contextmanager def open_input(fpath): fd = open(fpath) if fpath else sys.stdin try: yield fd

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

核能气质少年 提交于 2019-11-28 18:28:09
问题 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

Meaning of “with” statement without “as” keyword

梦想与她 提交于 2019-11-28 06:15:13
I'm familiar with using python's with statement as a means of ensuring finalization of an object in the event of an exception being thrown. This usually looks like with file.open('myfile.txt') as f: do stuff... which is short-hand for f = file.open('myfile.txt'): try: do stuff... finally: f.close() or whatever other finalization routine a class may present. I recently came across a piece of code dealing with OpenGL that presented this: with self.shader: (Many OpenGL commands) Note that absence of any as keyword. Does this indicate that the __enter__ and __exit__ methods of the class are still

Catching exception in context manager __enter__()

六月ゝ 毕业季﹏ 提交于 2019-11-28 04:33:45
Is it possible to ensure the __exit__() method is called even if there is an exception in __enter__() ? >>> class TstContx(object): ... def __enter__(self): ... raise Exception('Oops in __enter__') ... ... def __exit__(self, e_typ, e_val, trcbak): ... print "This isn't running" ... >>> with TstContx(): ... pass ... Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in __enter__ Exception: Oops in __enter__ >>> Edit This is as close as I could get... class TstContx(object): def __enter__(self): try: # __enter__ code except Exception as e self.init_exc

Context managers and multiprocessing pools

让人想犯罪 __ 提交于 2019-11-27 19:25:34
Suppose you are using a multiprocessing.Pool object, and you are using the initializer setting of the constructor to pass an initializer function that then creates a resource in the global namespace. Assume resource has a context manager. How would you handle the life-cycle of the context managed resource provided it has to live through the life of the process, but be properly cleaned up at the end? So far, I have something somewhat like this: resource_cm = None resource = None def _worker_init(args): global resource resource_cm = open_resource(args) resource = resource_cm.__enter__() From

Is it possible to access enclosing context manager?

被刻印的时光 ゝ 提交于 2019-11-27 17:36:01
问题 There are essentially three ways to use the with statement: Use an existing context manager: with manager: pass Create a context manager and bind its result to a variable: with Manager() as result: pass Create an context manager and discard its return value: with Manager(): pass If we have place a function get_manager() inside the three with blocks above, is there any implementation that can return the enclosing context manager, or at least their __exit__ function? It's obviously easy in the

Alternative to contextlib.nested with variable number of context managers

我怕爱的太早我们不能终老 提交于 2019-11-27 14:18:26
We have code that invokes a variable number of context managers depending on runtime parameters: from contextlib import nested, contextmanager @contextmanager def my_context(arg): print("entering", arg) try: yield arg finally: print("exiting", arg) def my_fn(items): with nested(*(my_context(arg) for arg in items)) as managers: print("processing under", managers) my_fn(range(3)) However, contextlib.nested is deprecated since Python 2.7 : DeprecationWarning: With-statements now directly support multiple context managers The answers to Multiple variables in Python 'with' statement indicate that

How to use socket in Python as a context manager?

雨燕双飞 提交于 2019-11-27 09:00:32
It seems like it would be only natural to do something like: with socket(socket.AF_INET, socket.SOCK_DGRAM) as s: but Python doesn't implement a context manager for socket. Can I easily use it as a context manager, and if so, how? Martijn Pieters The socket module is fairly low-level, giving you almost direct access to the C library functionality. You can always use the contextlib.contextmanager decorator to build your own: import socket from contextlib import contextmanager @contextmanager def socketcontext(*args, **kw): s = socket.socket(*args, **kw) try: yield s finally: s.close() with

Use a context manager for python script output to a file?

只愿长相守 提交于 2019-11-27 08:03:35
问题 I'm programming a script where I have an option, to be passed on the command line, whether the script should print its results to stdout or to a predefined results file. A code outline for this is shown below. I now have read a little bit about context managers in Python, but am not really sure whether and how to use a context manager in this specific situation. So I am looking for advice whether it makes sense to use a context manager in this problem how to go about implementing it. So, the