pycon logo

PyCon 2011 Atlanta

March 9th–17th

Log in or Sign Up

Useful Namespaces: Context Managers and Decorators

log in to bookmark this presentaton

Experienced / Talk
March 11th 2:15 p.m. – 2:45 p.m.
Python has two useful conventions for "I mean it, but only here" and you can say it with Context Managers and Decorators. Both give you the power to define a push/pop of a resource for a set period inside a namespace, be it a function or a level of indentation. This talk is a list of patterns that are implemented by one or the other (including some clever functions that are both).


  • Decorators, formal definition.
  • Context Managers, formal definition.
  • Informal definition: both have the opportunity to do and then undo. - very similar to C++ RIIA "Resource Acquisition Is Initialization." - Context Managers were designed to do that but decorators are frequently just as good.
  • Which one to use use when is all about namespaces. - Context Managers manipulate at the block level. - Function Decorators manipulate the function level. - Class Decorators manipulate at the class level.
  • Recipes on writing decorators and context managers - Familiar examples from Django and Mock.