Understanding the with statements

Last but not least, the with statement is usually used with any kind of connections or managed resources such as file handles. Consider the following example:

with open('./text_file.txt', 'r') as file:
data = file.read()

print(data)

Here, we use a with clause together with the open() function. The open function returns a file-like object that has __enter__ and __exit__ methods, representing the opening and closing of the file. Both can be used directly, but the file needs to be closed properly once it is opened. The close() function along together with the with clause does exactly that – it opens an object, and makes sure it is closed (using those two methods) at the end. Essentially, it is the equivalent of the following try/finally statement:

try:
file = open('./text_file.txt', 'r').__enter__()
data = file.read()
finally:
file.__exit__()

You can see that this statement is quite similar to try/finally, but definitely more expressive and clean. As always, with Python, with is designed around the duck typing principle (if it quacks like a duck and walks like a duck, consider it a duck): if any arbitrary object has __enter__ and __exit__ methods, it can be used in the with clause as the statement does not care what actually is happening in those functions. Most database connections and cursors support this feature.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.38.24