Doing magic with python metaclassesPresentation Transcript
Python Meta classes and how
Django uses them Lakshman Prasad
A Design pattern
Dynamically create classes
Enables Flexibility, Good API
Used by Frameworks
Where Meta Classes?
Frameworks, frameworks, frameworks.
Django uses them extensively.
Scrappy, a web scrapping framework.
Flexible Django apps. Eg: Django-registration
Executes the code when encountered
Creates namespace and stores all variables in it
`type` is an inbuilt MetaClass
Dynamic class = Static classes
`__metaclass__` defines metaclases
Meta Class Magic
Define a class extending object
Examined type is string, Magic!
Enables Declarative Syntax
MetaClasses, not always
Simple function decorators
Unintuitive to end developers, unless
Python 2.6+ has Class Decorators
But being powerful, where they are needed,
Django Models Creation
Declarative Syntax, No `__metaclass__`
New model created in place
Options into `Options` object
Register in registry called `AppCache`
Add attributes to new model
Inside Django Models
Return the same registered Model from
Original options and Meta options stored in
Add more useful attributes/classes like
`DoesnotExist`, `module_name` and
Rendering in html
Validation for right data
Provided model, storing to the database
Dynamic Django forms - 1
Forms API is flexible, but often needs Meta Classes
`base_fields` and `fields` list store all fields
Change field attributes while initialization
Dynamic Django Forms - 2
When high complexity, instantiate a form,
Python, Django Documentation, Source.
Pro Django, by Marty Alchin
Django-registration v0.7 by James Bennett
: Build Cutting Edge Web Apps.
Small Team of expert Django Developers.
Exclusively develop in Django, Python stack.