From cfd7277fe2ffad0c906ff714834ae169bae28c26 Mon Sep 17 00:00:00 2001 From: Mark Pilgrim Date: Sat, 26 Sep 2009 00:05:54 -0400 Subject: [PATCH] fix xref --- files.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/files.html b/files.html index d7deacf..31c6d32 100644 --- a/files.html +++ b/files.html @@ -216,7 +216,7 @@ ValueError: I/O operation on closed file.

Here’s the kicker: no matter how or when you exit the with block, Python will close that file… even if you “exit” it via an unhandled exception. That’s right, even if your code raises an exception and your entire program comes to a screeching halt, that file will get closed. Guaranteed.

-

In technical terms, the with statement creates a runtime context. In these examples, the stream object acts as a context manager. Python creates the stream object a_file and tells it that it is entering a runtime context. When the with code block is completed, Python tells the stream object that it is exiting the runtime context, and the stream object calls its own close() method. See Appendix B, “Context Managers” for details. +

In technical terms, the with statement creates a runtime context. In these examples, the stream object acts as a context manager. Python creates the stream object a_file and tells it that it is entering a runtime context. When the with code block is completed, Python tells the stream object that it is exiting the runtime context, and the stream object calls its own close() method. See Appendix B, “Classes That Can Be Used in a with Block” for details.

There’s nothing file-specific about the with statement; it’s just a generic framework for creating runtime contexts and telling objects that they’re entering and exiting a runtime context. If the object in question is a stream object, then it does useful file-like things (like closing the file automatically). But that behavior is defined in the stream object, not in the with statement. There are lots of other ways to use context managers that have nothing to do with files. You can even create your own, as you’ll see later in this chapter.