Decorators and Context Managers

Audience level:
Core Python (Language, Stdlib)
March 9th 3:20 p.m. – 3:50 p.m.


Learn how decorators and context managers work, see several popular examples, and get a brief intro to writing your own. Decorators wrap your functions to easily add more functionality. Context managers use the 'with' statement to make indented blocks magical. Both are very powerful parts of the python language; come learn how to use them in your code.


Decorators wrap or modify your functions. They are functions themselves, so you can pass parameters to them. You can wrap a function with multiple decorators too. We'll cover how to use decorators in all those situations and how to write them too. Examples will be demonstrated with:

  • @property
  • @memoize
  • mock/patch
  • TurboGears
  • Django
  • Allura

Context managers wrap a block of code using the 'with' statement to do something on the way into the block and something on the way out. Opening and closing a file is a very common case, but there is a lot more you can do. Examples include:

  • modifying state
  • capturing stdout
  • mock/patch
  • locks
  • timing
  • transactions

More about decorators:

More about context managers: