Context Managers and else Blocks

In this chapter, we will discuss control flow features that are not so common in other languages, and for this reason tend to be overlooked or underused in Python. They are:

  • The with statement and context managers
  • The else clause in for, while, and try statements

The with statement sets up a temporary context and reliably tears it down, under the control of a context manager object. This prevents errors and reduces boilterplate code, making APIs at the same time safer and easier to use. Python programmers are finding lots of uses for with blocks beyond automatic file closing.

 

 

 

 

 

 

 

 

 

 

end...

Guess you like

Origin www.cnblogs.com/neozheng/p/12446165.html