with expression [as name]
code block
What it boils down to is this: The with statement expects its expression to evaluate to an object that has two methods: __enter__ and __exit__. These will then be called before and after executing the code within the statement. To quote the article "Now, when the “with” statement is executed, Python evaluates the expression, calls the __enter__ method on the resulting value (which is called a “context guard”), and assigns whatever __enter__ returns to the variable given by as. Python will then execute the code body, and no matter what happens in that code, call the guard object’s __exit__ method. "
This means, that you can use the with statement for other things than merely locking (which is probably the mostly know use). Consider the code below:
with open('foo.txt', 'r') as infile:
print infile.read()
This would open the file, assign it the name infile in the statement code block, read and print the file, and finally close the file again. This is all because a file objects __enter__ method returns the opened file, and its __exit__ method closes the file. Pretty neat, huh? :-)
Good explanation. Thanks.
ReplyDeleteThanks man. Explained what I was looking for :)
ReplyDelete