contextmanager

Combine two context managers into one

我的梦境 提交于 2019-12-18 03:55:34
问题 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 回答1: 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

Combine two context managers into one

拟墨画扇 提交于 2019-12-18 03:55:06
问题 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 回答1: 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

Nesting Python context managers

冷暖自知 提交于 2019-12-17 19:59:27
问题 In this question, I defined a context manager that contains a context manager. What is the easiest correct way to accomplish this nesting? I ended up calling self.temporary_file.__enter__() in self.__enter__() . However, in self.__exit__ , I am pretty sure I have to call self.temporary_file.__exit__(type_, value, traceback) in a finally block in case an exception is raised. Should I be setting the type_, value, and traceback parameters if something goes wrong in self.__exit__ ? I checked

Python Multiprocessing Lib Error (AttributeError: __exit__)

梦想的初衷 提交于 2019-12-17 07:24:03
问题 Am getting this error when using the pool.map(funct, iterable) : AttributeError: __exit__ No Explanation, only stack trace to the pool.py file within the module. using in this way: with Pool(processes=2) as pool: pool.map(myFunction, mylist) pool.map(myfunction2, mylist2) I suspect there could be a problem with the picklability (python needs to pickle , or transform list data into byte stream) yet I'm not sure if this is true or if it is how to debug. EDIT: new format of code that produces

Naming convention for context-manager classes (“with” blocks)

荒凉一梦 提交于 2019-12-14 04:17:25
问题 Is there a general naming convention for classes or functions that are meant to be used in with block such as with CreateSomeContext() as x: ... ? Something that signals that the class or the result of a function should be used with with ? 回答1: There's no naming convention ( open , socket.create_connection , urllib.request.urlopen all return context managers which can be used with with ) but context managers will have the __enter__ and __exit__ methods. Note : in the case of open("file", "w")

How do I write a three-block context manager in Python?

一笑奈何 提交于 2019-12-13 16:03:16
问题 I have many functions that exploit the context manager pattern: @contextmanager def f(): # Do preliminary stuff. yield # Do final stuff. I use an ExitStack to call all of these context managers. I am considering the pattern: @threeblock_contextmanager def f(): # Do preliminary stuff. yield # Do intermediary stuff. yield # Do final stuff. I've been looking at the source and thought I would modify it in some way. Is there a nice way to accomplish this? My other option is to add a method to each

How to reuse a custom @contextlib.contextmanager?

做~自己de王妃 提交于 2019-12-13 14:26:08
问题 I'm trying to create a wrapper to make context objects optional. When the condition is true, the thing should behave like the wrapped context object, otherwise it should behave like a no-op context object. This example works for using the wrapped object once, but fails it it is reused. Example: import contextlib from threading import Lock @contextlib.contextmanager def conditional_context(context, condition): if condition and context: with context: yield else: yield use_locking = False lock =

Cleanly and optionally redirect stderr or stdout to file

女生的网名这么多〃 提交于 2019-12-12 04:59:40
问题 I have a Python3 script and I want to optionally redirect stdout and stderr to a file. Something like this: # variable declarations if log_output: output_file = open('output.txt', 'w') sys.stdout = output_file if log_errors: errors_file = open('errors.txt', 'w') sys.stderr = errors_file # code that uses variables declared above but may exit suddenly #at the end if log_output: output_file.close() if log_errors: errors_file.close() This works, unless my code in the middle decides to quit. Then

How to return from with statement?

喜你入骨 提交于 2019-12-11 11:33:57
问题 I have a function that tries some list of params to connect to ftp and connects to the first server that it could. def connect(params): for user, passw, host in params: try: import pdb;pdb.set_trace() with FTPHost(host, user, passw) as h: return h except FTPError as e: logger.debug("Can't connect to ftp error is {}".format(e)) else: raise Exception( "Can't connect to ftp server with none of the {}".format(params) ) Further in code I'm trying something like that host = connect(*args) host.walk

exc_value parameter from __exit__() (context manager) is string instead of Exception (Python 2.6)

北城以北 提交于 2019-12-11 11:29:29
问题 I tried to mess around with context managers and got a bit surprised when running my code with Python 2.6. Indeed, the exc_value parameter seems to be a string instead of an exception. A bit of code to hi-light this issue : import sys class contextmanager(object): def __enter__(self): pass def __exit__(self, type_, value, traceback): assert (type_ is None) == (value is None) if value is not None: print(type(value)) if __name__ == '__main__': print(sys.version_info) with contextmanager(): _