How do I mock an open used in a with statement (using the Mock framework in Python)?
How do I test the following code with unittest.mock: def testme(filepath): with open(filepath) as f: return f.read() 10 Answers 10
How do I test the following code with unittest.mock: def testme(filepath): with open(filepath) as f: return f.read() 10 Answers 10
This question already has answers here: Multiple variables in a ‘with’ statement? (8 answers) Closed 3 years ago. Suppose you have three objects you acquire via context manager, for instance A lock, a db connection and an ip socket. You can acquire them by: with lock: with db_con: with socket: #do stuff But is there … Read more
Consider the following: with open(path, mode) as f: return [line for line in f if condition] Will the file be closed properly, or does using return somehow bypass the context manager? 4 Answers 4
Alan Storm’s comments in response to my answer regarding the with statement got me thinking. I’ve seldom found a reason to use this particular language feature, and had never given much thought to how it might cause trouble. Now, I’m curious as to how I might make effective use of with, while avoiding its pitfalls. … Read more
I saw this in someone’s code. What does it mean? def __enter__(self): return self def __exit__(self, type, value, tb): self.stream.close() from __future__ import with_statement#for python2.5 class a(object): def __enter__(self): print ‘sss’ return ‘sss111’ def __exit__(self ,type, value, traceback): print ‘ok’ return False with a() as s: print s print s 7 s 7 Using these … Read more
I came across the Python with statement for the first time today. I’ve been using Python lightly for several months and didn’t even know of its existence! Given its somewhat obscure status, I thought it would be worth asking: What is the Python with statement designed to be used for? What do you use it … Read more
Is it possible to declare more than one variable using a with statement in Python? Something like: from __future__ import with_statement with open(“out.txt”,”wt”), open(“in.txt”) as file_out, file_in: for line in file_in: file_out.write(line) … or is cleaning up two resources at the same time the problem? 8 s 8