contextmanager

Trying to understand python with statement and context managers

情到浓时终转凉″ 提交于 2019-11-27 07:53:05
I am new to this, and am just trying to understand the with statement. I understand that it is supposed to replace the try / except block. Now suppose I do something like this: try: name='rubicon'/2 # to raise an exception except Exception as e: print "no not possible" finally: print "Ok I caught you" How do I replace this with a context manager? with doesn't really replace try / except , but, rather, try / finally . Still, you can make a context manager do something different in exception cases from non-exception ones: class Mgr(object): def __enter__(self): pass def __exit__(self, ext, exv,

Meaning of “with” statement without “as” keyword

泪湿孤枕 提交于 2019-11-27 05:39:01
问题 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

Python Multiprocessing Lib Error (AttributeError: __exit__)

余生颓废 提交于 2019-11-27 04:22:25
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 this error : def governingFunct(list): #some tasks def myFunction(): # function contents with closing

Python mock builtin 'open' in a class using two different files

匆匆过客 提交于 2019-11-27 02:41:17
问题 I am having trouble figuring out how to mock two file opens in a class when they both use context managers. I know how to do it for one context-managed file using the mock module like this: @patch('__builtin__.open') def test_interface_mapping(self, mock_config): m = MagicMock(spec=file) handle = m.return_value.__enter__.return_value handle.__iter__.return_value = ('aa', 'bb') My problem is how to do this when a class opens two different files in the same call. In my case, the class __init__(

Catching exception in context manager __enter__()

烂漫一生 提交于 2019-11-27 00:29:49
问题 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...

Context managers and multiprocessing pools

十年热恋 提交于 2019-11-26 22:48:20
问题 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

Context manager for Python's MySQLdb

家住魔仙堡 提交于 2019-11-26 20:00:31
问题 I am used to (spoiled by?) python's SQLite interface to deal with SQL databases. One nice feature in python's SQLite's API the "context manager," i.e., python's with statement. I usually execute queries in the following way: import as sqlite with sqlite.connect(db_filename) as conn: query = "INSERT OR IGNORE INTO shapes VALUES (?,?);" results = conn.execute(query, ("ID1","triangle")) With the code above, if my query modifies the database and I forget to run conn.commit() ,the context manager

Alternative to contextlib.nested with variable number of context managers

无人久伴 提交于 2019-11-26 16:39:59
问题 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

How to use socket in Python as a context manager?

筅森魡賤 提交于 2019-11-26 14:26:26
问题 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? 回答1: 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

Trying to understand python with statement and context managers

纵饮孤独 提交于 2019-11-26 13:56:03
问题 I am new to this, and am just trying to understand the with statement. I understand that it is supposed to replace the try / except block. Now suppose I do something like this: try: name='rubicon'/2 # to raise an exception except Exception as e: print "no not possible" finally: print "Ok I caught you" How do I replace this with a context manager? 回答1: with doesn't really replace try / except , but, rather, try / finally . Still, you can make a context manager do something different in