Anyone familiar with this pattern knows that invoking open
in this fashionensures that f
’s close
method will be called at some point. This reducesa developer’s cognitive load and makes the code easier to read.
This is just a regular Python object with two extra methods that are usedby the with
statement. CustomOpen is first instantiated and then its method is called and whatever enter
returns is assigned tof
in the as f
part of the statement. When the contents of the with
blockis finished executing, the exit
method is then called.
This works in exactly the same way as the class example above, albeit it’smore terse. The function executes until it reaches the yield
statement. It then gives control back to the with
statement, which assignswhatever was yield
’ed to _f in the as f
portion. The finally
clauseensures that is called whether or not there was an exception insidethe with
.