Python Metaclasses

Post on 25-Jun-2015

398 views 3 download

Tags:

description

A talk i did at PyConZA 2013

Transcript of Python Metaclasses

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

SOME BASICS

Everything is an object in python.

Classes create instances.

Class Foo(object):

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

f = Foo(‘Alex Bar’)

type(f)

Creating new types

Class Foo(object): pass

Class Foo: pass

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

type(cls,*args,**kwargs)

type() is actually not a function.

It is a META CLASS.

A special kind of class that creates classes.

type(name, bases, cls_dct)

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

At runtime class Foo is an instance of type

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

_ _new_ _() vs _ _init_ _()

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

class Foo(metaclass = Meta):

def _ _init_ _(self): pass

Show us the code

Example #1

Making a class final

Example #2

Decorating class methods

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

Some advanced basics

A class is an instance of its metaclass at runtime.

Metaclasses go down the inheritance chain.

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

With great power comes great responsibility

Questions ???