python metaclasses

28
Python Meta Classes Kisitu Augustine Software Developer at ThoughtWorks Twitter: @austiine04 Github: austiine04

Upload: kisitu-augustine

Post on 25-Jun-2015

407 views

Category:

Technology


3 download

DESCRIPTION

A talk i did at PyConZA 2013

TRANSCRIPT

Page 1: Python Metaclasses

Python Meta ClassesKisitu AugustineSoftware Developer at ThoughtWorksTwitter: @austiine04Github: austiine04

Page 2: Python Metaclasses

SOME BASICS

Page 3: Python Metaclasses

Everything is an object in python.

Page 4: Python Metaclasses

Classes create instances.

Class Foo(object):

def _ _init_ _(self, bar): self.bar = bar

f = Foo(‘Alex Bar’)

Page 5: Python Metaclasses

type(f)

Page 6: Python Metaclasses

Creating new types

Page 7: Python Metaclasses

Class Foo(object): pass

Page 8: Python Metaclasses

Class Foo: pass

Page 9: Python Metaclasses

Foo = type(‘Foo’, (), {})

Page 10: Python Metaclasses

type(cls,*args,**kwargs)

Page 11: Python Metaclasses

type() is actually not a function.

It is a META CLASS.

Page 12: Python Metaclasses

A special kind of class that creates classes.

Page 13: Python Metaclasses

type(name, bases, cls_dct)

Page 14: Python Metaclasses

Class Foo(object): def _ _init_ _(self, bar): self.bar = bar

At runtime class Foo is an instance of type

Page 15: Python Metaclasses

Defining a meta class

class Meta(type):

def _ _init_ _(cls, name, bases, dict): pass

def _ _new_ _(meta, name, bases, dct): pass def _ _call_ _(cls, *args, **kwargs): pass

*remember to call super in each of method you override

Page 16: Python Metaclasses

_ _new_ _() vs _ _init_ _()

Page 17: Python Metaclasses

class Foo(object): _ _metaclass_ _ = Meta def _ _init_ _(self): pass

Page 18: Python Metaclasses

class Foo(metaclass = Meta):

def _ _init_ _(self): pass

Page 19: Python Metaclasses

Show us the code

Page 20: Python Metaclasses

Example #1

Making a class final

Page 21: Python Metaclasses

Example #2

Decorating class methods

Page 22: Python Metaclasses

def log(function): def wrapper_function(*args, **kwargs): print “Calling ……….”, function.__name__ return function(*args, **kwargs) return wrapper_function

Page 23: Python Metaclasses

Some advanced basics

Page 24: Python Metaclasses

A class is an instance of its metaclass at runtime.

Page 25: Python Metaclasses

Metaclasses go down the inheritance chain.

Page 26: Python Metaclasses

Things can get quite ugly if you are inheriting from multiple classes each with its own meta class.

Page 27: Python Metaclasses

With great power comes great responsibility

Page 28: Python Metaclasses

Questions ???