Questions tagged [with-statement]

A number of languages have With statements. The Python with statement creates a new context, with associated context manager. When the context (a code block) is exited again, the context manager is notified. Please use "common-table-expression" for the SQL WITH construction.

A number of languages have With statements. Python's with statement creates a runtime context, defined by a . As the code block under the with statement is entered, a __enter__ hook is called on the context manager, and as it is exited (by any means, including exceptions and return statements), the __exit__ hook is called.

Python provides several standard context managers. File objects, for example, can be opened as a context manager, and on exit the file is automatically closed.

Context managers were defined in PEP 343.

Please use for the SQL WITH statement

945 questions
465
votes
8 answers

Multiple variables in a 'with' statement?

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: …
pufferfish
  • 14,144
  • 13
  • 52
  • 61
448
votes
11 answers

What is the python "with" statement designed for?

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…
fmark
  • 50,804
  • 25
  • 88
  • 106
427
votes
7 answers

Explaining Python's '__enter__' and '__exit__'

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…
zjm1126
  • 52,371
  • 71
  • 163
  • 213
381
votes
32 answers

Are there legitimate uses for JavaScript's "with" statement?

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…
Shog9
  • 146,212
  • 34
  • 221
  • 231
303
votes
4 answers

In Python, if I return inside a "with" block, will the file still close?

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?
Lightbreeze
  • 3,404
  • 3
  • 13
  • 10
229
votes
5 answers

Create a "with" block on several context managers?

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 a way to do it in one…
olamundo
  • 21,047
  • 32
  • 99
  • 142
225
votes
10 answers

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()
Daryl Spitzer
  • 121,723
  • 75
  • 151
  • 166
106
votes
4 answers

Using python "with" statement with try-except block

Is this the right way to use the python "with" statement in combination with a try-except block?: try: with open("file", "r") as f: line = f.readline() except IOError: If it is, then considering the old way of doing…
gaefan
  • 14,322
  • 16
  • 52
  • 100
90
votes
3 answers

Implementing use of 'with object() as f' in custom class in python

I have to open a file-like object in python (it's a serial connection through /dev/) and then close it. This is done several times in several methods of my class. How I WAS doing it was opening the file in the constructor, and then closing it in the…
Falmarri
  • 44,586
  • 38
  • 140
  • 186
86
votes
8 answers

Conditional with statement in Python

Is there a way to begin a block of code with a with statement, but conditionally? Something like: if needs_with(): with get_stuff() as gs: # do nearly the same large block of stuff, # involving gs or not, depending on needs_with() To clarify,…
72
votes
10 answers

The VB.NET 'With' Statement - embrace or avoid?

At work, I'm frequently working on projects where numerous properties of certain objects have to be set during their construction or early during their lifetime. For the sake of convenience and readability, I often use the With statement to set…
Tom
  • 13,740
  • 4
  • 45
  • 60
57
votes
2 answers

Django {% with %} tags within {% if %} {% else %} tags?

So I want to do something like follows: {% if age > 18 %} {% with patient as p %} {% else %} {% with patient.parent as p %} ... {% endwith %} {% endif %} But Django is telling me that I need another {% endwith %} tag. Is there any way…
Kelly Nicholes
  • 573
  • 1
  • 4
  • 4
52
votes
6 answers

Python multi-line with statement

What is a clean way to create a multi-line with in python? I want to open up several files inside a single with, but it's far enough to the right that I want it on multiple lines. Like this: class Dummy: def __enter__(self): pass def…
Justin
  • 21,374
  • 12
  • 83
  • 129
52
votes
12 answers

Break or exit out of "with" statement?

I'd just like to exit out of a with statement under certain conditions: with open(path) as f: print 'before condition' if : break #syntax error! print 'after condition' Of course, the above doesn't work. Is there a way to do…
jmilloy
  • 6,690
  • 7
  • 46
  • 79
50
votes
3 answers

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

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…
mpettis
  • 2,468
  • 4
  • 19
  • 29
1
2 3
62 63