Useful Namespaces: Context Managers and Decorators

Description

Useful Namespaces: Context Managers and Decorators

Presented by Jack Diederich

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).

Abstract

  • 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.