Advanced Python : Decorators


Published on

This slide gives quick introduction to function and class decorators in python with easy to understand examples.

Published in: Education, Technology

Advanced Python : Decorators

  1. 1. Decorators in PythonBhanwar Singh
  2. 2. Functions are Objects• They can be assigned to other variables.• A function can be defined inside anotherfunction.• A function can return another function.• A function can take other function as anarguments.
  3. 3. Decorators• A decorator is used to wrap a function.• It gives new functionality without changingthe original function.Syntax :@decorator_functiondef my_func:…………………….…………………….def decorater_function():……………………….……………………….This is equivalent to :my_func =decorator_function(my_func)
  4. 4. How to define a decorator function?• It takes a function (the one being decorated),wrap it in a wrapper function and then returnthe wrapper function.def decorator_function(decorated_function):def wrapper_function():------------------------------------------- some code ----------------decorated_function()------------------------------------return wrapper_function
  5. 5. • There are user defined and in built decorators.staticmethod and classmethod areexample of in built decorators.• There can be more that one decorator for onefunction. They are executed using stack.
  6. 6. Exampledef helloSolarSystem(old_function):def wrapper_function():print "Hello Solar System"old_function()return wrapper_functiondef helloGalaxy(old_function):def wrapper_function():print "Hello Galaxy"old_function()return wrapper_function@helloGalaxy@helloSolarSystemdef hello():print "Hello World"hello()The output will be -Hello GalaxyHello Solar SystemHello WorldFirst all decorators arepushed into a stackThen, at last, they arepopped one by one.
  7. 7. Passing argument to the decorated functionThe wrapper function should accept the arguments which are being passed to thefunction being decorated.def helloSolarSystem(old_function):def wrapper_function(planet=None):print "Hello Solar System"old_function(planet)return wrapper_function@helloSolarSystemdef hello(planet=None):if planet:print "Hello "+planetelse:print "Hello World"hello("Mars")hello()OutputHello Solar SystemHello MarsHello Solar SystemHello World
  8. 8. • You can also define wrapper for class method.But their first argument should be self• You can define general wrapper function using*args, **kwargs.
  9. 9. Class Decorators• Class decorators are similar to functiondecorators.• They are run at the end of a class statement torebind a class name to a callable.• They can be used to manage class when they arecreated.• They can be used to insert a layer of wrapperlogic to manage instances.• Remember both class and class instance areobject in python.
  10. 10. Syntax• Syntax is similar to function decorator.Class definition-@class_decoratorclass My_Class:--------------------------Decorator definition –def class_decorator(cls):------------------------------This is equivalent toMy_Class =class_decorator(My_Class)
  11. 11. Example – Singleton Classinstances = {} #dictionary to hold class and their only instancedef getInstance(klass,*args): #this function is used by decoratorif klass not in instances:instances[klass]=klass(*args)return instances[klass]def singelton(klass): #decorator functiondef onCall(*args):return getInstance(klass,*args)return onCall@singeltonclass Star:def __init__(self,name) solar system should have only one starsun = Star(Sun)print sun.nametaurus = Star(Taurus)print taurus.nameOutput -SunSunOnly one instance of Star is allowed.
  12. 12. Sources -
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.