O'Reilly logo

Python Parallel Programming Cookbook by Giancarlo Zaccone

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using the with statement

Python's with statement was introduced in Python 2.5. It's useful when you have two related operations that must be executed as a pair with a block of code in between. Also, with the with statement, you can allocate and release some resource exactly where you need it; for this reason, the with statement is called a context manager. In the threading module, all the objects provided by the acquire() and release() methods may be used in a with statement block.

So the following objects can be used as context managers for a with statement:

  • Lock
  • RLock
  • Condition
  • Semaphore

Getting ready

In this example, we simply test all the objects using the with statement.

How to do it…

This example shows the basic use of the with statement. We have ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required