contextmanager

In python, is there a good idiom for using context managers in setup/teardown

那年仲夏 提交于 2019-11-30 11:16:07
问题 I am finding that I am using plenty of context managers in Python. However, I have been testing a number of things using them, and I am often needing the following: class MyTestCase(unittest.TestCase): def testFirstThing(self): with GetResource() as resource: u = UnderTest(resource) u.doStuff() self.assertEqual(u.getSomething(), 'a value') def testSecondThing(self): with GetResource() as resource: u = UnderTest(resource) u.doOtherStuff() self.assertEqual(u.getSomething(), 'a value') When this

Python2.7 contextlib.ExitStack equivalent

你离开我真会死。 提交于 2019-11-30 09:11:12
问题 To programmatically combine context managers I use the following code: == helpers.py == from contextlib import nested import mock def multiple_patch(obj_to_be_patch, *methods): return nested( *[mock.patch.object(obj_to_be_patch, method) for method in methods] ) == tests.py == def test_foo(self): with helpers.multiple_patch(Foo, "method1", "method2", "method3", "method3") as mocks: mock_method1 = mocks[0] .... # asserts on mocks Because I'm stuck with this version of python I can't use

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

天大地大妈咪最大 提交于 2019-11-30 04:48:33
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 finally: fd.close() with open_input("/path/to/file"): print "starting to read from file..." the same

Asynchronous context manager

瘦欲@ 提交于 2019-11-30 04:27:13
I have an asynchronous API which I'm using to connect and send mail to an SMTP server which has some setup and tear down to it. So it fits nicely into using a contextmanager from Python 3's contextlib . Though, I don't know if it's possible write because they both use the generator syntax to write. This might demonstrate the problem (contains a mix of yield-base and async-await syntax to demonstrate the difference between async calls and yields to the context manager). @contextmanager async def smtp_connection(): client = SMTPAsync() ... try: await client.connect(smtp_url, smtp_port) await

In python, is there a good idiom for using context managers in setup/teardown

北城以北 提交于 2019-11-30 01:45:51
I am finding that I am using plenty of context managers in Python. However, I have been testing a number of things using them, and I am often needing the following: class MyTestCase(unittest.TestCase): def testFirstThing(self): with GetResource() as resource: u = UnderTest(resource) u.doStuff() self.assertEqual(u.getSomething(), 'a value') def testSecondThing(self): with GetResource() as resource: u = UnderTest(resource) u.doOtherStuff() self.assertEqual(u.getSomething(), 'a value') When this gets to many tests, this is clearly going to get boring, so in the spirit of SPOT/DRY (single point of

python contextmanager newline issue

廉价感情. 提交于 2019-11-29 14:39:35
Using Python's contextmanager I want to generate a wrapper to display Linux-like progress of a certain block of code: Doing something... done. [42 ms] This is working - kind of: from contextlib import contextmanager import time @contextmanager def msg(m): print(m + "... ", end='') t_start = time.time() yield t_duration_ms = 1000 * (time.time() - t_start) print("done. [{:.0f} ms]".format(t_duration_ms)) This usage example should print "Doing something... " without a line break, wait for a second, print "done. [1000 ms]" including a line break and quit. with msg("Doing something"): time.sleep(1)

How to use the context manager to avoid the use of __del__ in python?

旧巷老猫 提交于 2019-11-29 13:59:55
问题 As it is common knowledge the python __del__ method should not be used to clean up important things, as it is not guaranteed this method gets called. The alternative is the use of a context manager, as described in several threads. But I do not quite understand how to rewrite a class to use a context manager. To elaborate, I have a simple (non-working) example in which a wrapper class opens and closes a device, and which shall close the device in any case the instance of the class gets out of

Python2.7 contextlib.ExitStack equivalent

妖精的绣舞 提交于 2019-11-29 13:25:49
To programmatically combine context managers I use the following code: == helpers.py == from contextlib import nested import mock def multiple_patch(obj_to_be_patch, *methods): return nested( *[mock.patch.object(obj_to_be_patch, method) for method in methods] ) == tests.py == def test_foo(self): with helpers.multiple_patch(Foo, "method1", "method2", "method3", "method3") as mocks: mock_method1 = mocks[0] .... # asserts on mocks Because I'm stuck with this version of python I can't use contextlib.ExitStack and contextlib.nested is deprecated. Thanks Check out contextlib2.ExitStack , a backport

Context manager to validate data

ぐ巨炮叔叔 提交于 2019-11-29 12:30:42
I'm trying to mull over a good solution to this and nothing is coming to mind. As an exercise, I'm trying to create a context manager that will handle data validation, something like: validation = lambda x: len(x) <= 10 with validator(validation): some_data = input("Please enter a name of 10 characters or less: ") print(some_data) # OUTPUT >> Please enter a name of 10 characters or less: FooBarSpamEggs >> Please enter a name of 10 characters of less: Adam Adam Originally I thought about doing this with unittest.mock.patch but I realized I can't call the original function while it's patched, e

Is it possible to access enclosing context manager?

时光总嘲笑我的痴心妄想 提交于 2019-11-29 03:29:49
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 first case, but I can't think of a way to make it work in the other two. I doubt it's possible to get