with
python compound statement in depth [ADVANCE]:with
is ported into python in version 2.5
.with
is used to wrap the execution of a code block using methods defined by a context manager.The process of
with
statement:- The expression given in front of with statement is evaluated to obtain a context manager.
- The context manager’s __exit__() is loaded (it is not executed, it is just loaded for later use).
- The context manager’s __enter__() method is invoked.
- If a target was included in the with statement, the return value from __enter__() is assigned to it (like opening a file)
- The suite is executed (your code block)
- The context manager’s __exit__() method is invoked.
Now consider the example below:
with VAR = EXPR:
BLOCK
Would roughly translates to:
VAR = EXPR
VAR.__enter__()
try:
BLOCK
finally:
VAR.__exit__()
The moral of the story is that when you open a file it will close the file automatically at the end:
@contextmanager
def opening(filename):
f = open(filename)
try:
yield f
finally:
f.close()
At the
finally
stage, the file will always be closed, and you don't need to manage it.Another example:
f = open(filename)
with f:
BLOCK1
with f:
BLOCK2
NOTE:
The above code does not do what one might think (f is closed before BLOCK2 is entered!).List of types which can be as a context manager (can be used in `with`):
- file
- thread.LockType
- threading.Lock
- threading.RLock
- threading.Condition
- threading.Semaphore
- threading.BoundedSemaphore
What is a
context manager
: it is an object that consists of __enter__()
and __exit__()
methods.What is a
context expression
: the expression immediately following the with
keyword in the statement is a context expression
.There is more about
with
to talk about, but I think it is more advanced and not needed for the time being :)#python #with #context_manager #with_statement #advance