The semantic of the with statement
The following code:
with EXPRESSION as TARGET:
SUITE |
is semantically equivalent to:
manager = (EXPRESSION) enter = type(manager).__enter__ exit = type(manager).__exit__ value = enter(manager) hit_except = False try: TARGET = value SUITE except: hit_except = True if not exit(manager, *sys.exc_info()): raise finally: if not hit_except: exit(manager, None, None, None) |
Similarly to the Java with statement
, the with statement
in python
allows to perform processing
that requires resource opening and to close resources automatically when it is done.
About exception inside the « with statement »: the program is stopped only if the resource manager
considers that the code return is « problematic »(in this case the manager exit()
function returns false).
Caching explicitly an exception inside the « with statement »
The behavior of the resource manager is very generic. In some cases, we want to perform a
different behavior, for example:
– performing a processing in case of detected exception.
– going on the execution even if the resource manager considers the exit code return as
problematic.
Here is the syntax we will use for that:
try: with EXPRESSION as TARGET: SUITE except Exception as e: process_exception(...) |
Examples
Open a file and read it line by line
Here we don’t specify a try catch
statement, so an exception occurring during the
body of the with statement
may make the execution to be terminated.
f='foo file' with open(f) as file: for i, line in enumerate(file): print(f'line({i})={line}') |
Open a file and read it line by line and catching any exception occurring during the processing
Here the processing may also be terminated if an exception is detected but the difference is that we perform a specific post processing if it happens.
f='foo file' try: with open(f) as file: for i, line in enumerate(file): print(f'line({i})={line}') except Exception as e: process_exception(...) |
Open sequentially files and read them line by line and going on with the next file when an error is detected
for f in files: try: with open(f) as file: i = 0 line = None for i, line in enumerate(file): print(f'line({i})={line}') except Exception as e: process_exception('An exception was detected during the processing of the file, we continue with the next file') |