12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The expression here is assumed to return an object that supports the context managementprotocol (more on this protocol in a moment). This object may also return avalue that will be assigned to the name variable if the optional as clause is present.Note that the variable is not assigned the result of the expression; the result of theexpression is the object that supports the context protocol, and the variable may beassigned something else. The object returned by the expression may then run startupcode before the with-block is started, as well as termination code after the block isdone, whether the block raised an exception or not.Some built-in <strong>Python</strong> objects have been augmented to support the context managementprotocol, and so can be used with the with statement. For example, file objectshave a context manager that automatically closes the file after the with block, regardlessof whether an exception is raised:with open(r'C:\python\scripts') as myfile:for line in myfile:print lineline = line.replace('spam', 'SPAM')...more code here...Here, the call to open returns a simple file object that is assigned to the name myfile.We can use myfile with the usual file tools—in this case, the file iterator reads lineby line in the for loop.However, this object also supports the context management protocol used by thewith statement. After this with statement has run, the context management machineryguarantees that the file object referenced by myfile is automatically closed, evenif the for loop raised an exception while processing the file.We won’t cover <strong>Python</strong>’s multithreading modules in this book (for more on thattopic, see follow-up application-level texts such as Programming <strong>Python</strong>), but thelock and condition variable synchronization tools they define also support the withstatement by supporting the context management protocol:lock = threading.Lock( )with lock:# critical section of code...access shared resources...Here, the context management machinery guarantees that the lock is automaticallyacquired before the block is executed and released once the block is complete.The decimal module (see Chapter 5 for more on decimals) also uses context managersto simplify saving and restoring the current decimal context, which specifies theprecision and rounding characteristics for calculations.with/as Context Managers | 597

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!