When to use Python's Decorators, Context Managers, Generators and Metaclasses
When to use Decorators
- Add functionality before or after a function is executed.
- Data sanitization or addition.
- Function or class registration.
When to use Context Managers
- Resource cleanliness (cleaning up after your code block).
- Handling exceptions, avoiding repetition.
When to use Generators
- Accessing data in pieces.
- Computing data in pieces.
When to use Metaclasses
- Modify class structure from the way it was declared, (e.g. Django model).
- Class verification (ensure class conforms to a particular interface).
- Non-inheriting attributes. e.g. make an abstract class not inherit attributes.
- Class registration.
Some of this was taken from Professional Python by Luke Sneeringer.