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

1119 questions
60
votes
4 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
  • 3,222
  • 4
  • 28
  • 35
58
votes
7 answers

pass argument to __enter__

Just learning about with statements especially from this article question is, can I pass an argument to __enter__? I have code like this: class clippy_runner: def __enter__(self): self.engine = ExcelConnection(filename =…
Ramy
  • 20,541
  • 41
  • 103
  • 153
53
votes
2 answers

Meaning of "with" statement without "as" keyword

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 =…
KDN
  • 1,349
  • 2
  • 14
  • 17
51
votes
5 answers

Invoking a constructor in a 'with' statement

I have the following code: class Test: def __init__(self, name): self.name = name def __enter__(self): print(f'entering {self.name}') def __exit__(self, exctype, excinst, exctb) -> bool: print(f'exiting…
Ian Newson
  • 7,679
  • 2
  • 47
  • 80
51
votes
2 answers

tempfile.TemporaryDirectory context manager in Python 2.7

Is there a way to create a temporary directory in a context manager with Python 2.7? with tempfile.TemporaryDirectory() as temp_dir: # modify files in this dir # here the temporary diretory does not exist any more.
guettli
  • 25,042
  • 81
  • 346
  • 663
49
votes
3 answers

How "with" is better than try/catch to open a file in Python?

I got that the with statement help you to turn this: try: f = open(my_file) do_stuff_that_fails() except: pass finally: f.close() Into: with open(my_file) as f: do_stuff_that_fails() But how is that better? You still have to…
Bite code
  • 578,959
  • 113
  • 301
  • 329
45
votes
2 answers

Is it safe to combine 'with' and 'yield' in python?

It's a common idiom in python to use context manager to automatically close files: with open('filename') as my_file: # do something with my_file # my_file gets automatically closed after exiting 'with' block Now I want to read contents of…
lesnik
  • 2,507
  • 2
  • 25
  • 24
40
votes
2 answers

What are the python builtin __exit__ argument types?

Classes have a defineable function __exit__ that allows implementation of a context manager. It takes the required arguments: def __exit__(self, exc_type, exc_val, exc_tb): but I cannot find a definitive definition of what those arguments are and…
notacorn
  • 3,526
  • 4
  • 30
  • 60
40
votes
8 answers

Skipping execution of -with- block

I am defining a context manager class and I would like to be able to skip the block of code without raising an exception if certain conditions are met during instantiation. For example, class My_Context(object): def __init__(self,mode=0): …
Macad_hack
  • 491
  • 7
  • 11
39
votes
6 answers

RAII in Python - automatic destruction when leaving a scope

I've been trying to find RAII in Python. Resource Allocation Is Initialization is a pattern in C++ whereby an object is initialized as it is created. If it fails, then it throws an exception. In this way, the programmer knows that the object will…
markets
  • 9,344
  • 7
  • 34
  • 33
39
votes
2 answers

Python Multiprocessing Lib Error (AttributeError: __exit__)

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) …
sidewaiise
  • 1,445
  • 3
  • 16
  • 27
38
votes
3 answers

Python __enter__ / __exit__ vs __init__ (or __new__) / __del__

I have searched and I'm unable to come up with any good reason to use python's __enter__ /__exit__ rather than __init__ (or __new__ ?) / __del__ . I understand that __enter__ / __exit__ are intended for use with the with statement as context…
BobDoolittle
  • 1,326
  • 1
  • 12
  • 21
38
votes
5 answers

Encapsulating retries into `with` block

I'm looking to encapsulate logic for database transactions into a with block; wrapping the code in a transaction and handling various exceptions (locking issues). This is simple enough, however I'd like to also have the block encapsulate the…
Michael Waterfall
  • 20,497
  • 27
  • 111
  • 168
36
votes
5 answers

Python Conditional "With" Lock Design

I am trying to do some shared locking using with statements def someMethod(self, hasLock = False): with self.my_lock: self.somethingElse(hasLock=True) def somethingElse(self, hasLock = False): #I want this to be conditional... …
Nix
  • 57,072
  • 29
  • 149
  • 198
36
votes
3 answers

Alternative to contextlib.nested with variable number of context managers

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: …
ecatmur
  • 152,476
  • 27
  • 293
  • 366
1
2
3
74 75