18
Python Meta classes and how Django uses them Lakshman Prasad

Doing magic with python metaclasses

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Doing magic with python metaclasses

Python Meta classes and how Django uses them

Lakshman Prasad

Page 2: Doing magic with python metaclasses

Meta Classes

A Design pattern

Dynamically create classes

Enables Flexibility, Good API

Used by Frameworks

Perform “Magic”

Page 3: Doing magic with python metaclasses

Where Meta Classes?

Frameworks, frameworks, frameworks.

Django uses them extensively.

Scrappy, a web scrapping framework.

Flexible Django apps. Eg: Django-registration

Page 4: Doing magic with python metaclasses
Page 5: Doing magic with python metaclasses

Executes the code when encountered

Creates namespace and stores all variables in it

Page 6: Doing magic with python metaclasses

`type` is an inbuilt MetaClass

Dynamic class = Static classes

Page 7: Doing magic with python metaclasses

`__metaclass__` defines metaclases

Page 8: Doing magic with python metaclasses

Meta Class Magic

Define a class extending object

Examined type is string, Magic!

Enables Declarative Syntax

Page 9: Doing magic with python metaclasses

MetaClasses, not always

Simple function decorators

Unintuitive to end developers, unless explained

Python 2.6+ has Class Decorators

But being powerful, where they are needed, indespesible

Page 10: Doing magic with python metaclasses

Django Models

Page 11: Doing magic with python metaclasses

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

Page 12: Doing magic with python metaclasses

Inside Django Models

Return the same registered Model from AppCache

Original options and Meta options stored in `_meta`

Add more useful attributes/classes like `DoesnotExist`, `module_name` and `class_name`

Page 13: Doing magic with python metaclasses

Django Forms

Page 14: Doing magic with python metaclasses

Rendering in html

Validation for right data

Displaying errors

Customization options

Provided model, storing to the database

Page 15: Doing magic with python metaclasses

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

Page 16: Doing magic with python metaclasses

Dynamic Django Forms - 2

When high complexity, instantiate a form, dynamically

Page 17: Doing magic with python metaclasses

Resources

Python, Django Documentation, Source.

Pro Django, by Marty Alchin

Django-registration v0.7 by James Bennett

Page 18: Doing magic with python metaclasses

Thank You!

[email protected]

: Build Cutting Edge Web Apps.

Small Team of expert Django Developers.

Exclusively develop in Django, Python stack.

@becomingGuru, @uswaretech