Search This Blog

Friday 25 April 2014

Decorators

Hi,

Here we will learn what is decorator.
Before that, you may think about decorators are same as Annotations in Java which follows '@' symbol. but in java, Annotation is like telling something to JVM. But here, in Python, Decorators are more than what you are expecting. It is not only just a representation, but also a powerful tool to alter your class, function or any object's functionality on the fly at runtime.
    
    OK, now what is Decorator?
                    Decorator is function or class, which takes another function/class as argument and applies extra features to existing and returns new class/functions.

Simply, it is a process of changing object(everything in Python is Object) at run time.

first we will discuss about inbuilt decorators and then, we will learn how to create our own decorators in Python.

1. @staticmethod
2. @classmethod

1. @staticmethod: By using this decorator, we can call methods from class directly by using class name.
for this, we do not need to create instance of class.

>>>class MyStaticClass(object):
              def  __init__(self):                     
                      pass

              @staticmethod
               def print_value():
                     print 'this is static method'

>>>MyStaticClass.print_value()
this is static method 

In this example, we are not creating any instance of the MyStaticClass class, simply we are calling method direcly by using class name. note that, since it is not instance member, Python never pass instance reference to that method. that is the reason why we are not providing a first default parameter in method which are declared with @staticmethod decorator.

2. @classmethod : This is also predefined decorator which is useful to bind method to class instead of instance. we can call these methods by using class name or using instance or both.

>>>class MyClassMethod(object):
               val = 5
               def __init__(self):
                     pass
               
               @classmethod
               def print_value(cls):
                     print 'given value is '+str(cls.val)

>>>mycls = MyClassMethod()
>>>mycls.print_value()
given value is 5
>>>MyClassMethod.print_value()
given value is 5

Here, we can call class method either by using class name, or by using instance.
This kind of usage is very helpful to create instance on the fly in the middle of program excution.

How to create our own Decorators ?

       In Python, it is possible to create our own decorators to alter object on the fly.

We can create decorators in two ways:
            1. class decorators
            2. function decorators

1. class decorators:  In this case, we can use our own class as a decorator to the another functions.
when compiler goes to the function compilation which is being decorated, it compiles the function first and sends the function object to the class decorator for producing substitution of the function.

       Only constraint on decorators object return is it should be a function. That is it should be callable. for these we need to override __call__() method in our decorator class as follows:

>>> class MyDecorator(object):
          def __init__(self,func):
              print "inside __init__() method"
              func()
             
          def __call__(self):
              print "inside __call__ () method"

>>>@MyDecorator
   def decFunction():
       print "inside function"

output:
inside __init__() method
inside function
inside __call__()

@MyDecorator
def decFunction():
      ......

is equal to 

defFunction = MyDecorator(defFunction)

simpley, it is a process of sending function object through another function or class and assign the result to the original function


2. function decorators:   when you are using decorators, only constrain is it should be callable. i.e. every decorator class should have to override __call__() method.

     Instead of overriding __call__() special function, we can rewrite decorator as follows:

>>>def entryExit(func):
       def new_f():
           print "entering function decorator"
           func()
           print "exit function decorator"
       retunr new_f

>>>@entryExit
   def function():
       print "inside function"

output:
entering function decorator
inside function
exit function decorator

Note that new_f() is a closure because it is capturing the func() method properties

behind the scene, Python compiles function method and sends to entryExit decorator as a parameter. it will executes as closure and output will come as new modified function execution.

By using decorator, we can create an instance which will acts as a another decorator for another class.
simply, decorators are very easy and very complex to use. 
a simple decorators are like "function acts as decorator to another function"
a complex decorators like "a decorator which is a decorator of decorator's decorator and returns decorator's decorator"

 simply, decorators are very powerful in Python.

 

Thursday 10 April 2014

How to install Python2.7 in linux machines ?

Installing Python in windows is just one click matter. Since we do not have any binaries for Linux machines. it is complicated than windows installation.
for this, we have some sort of process which is easy way to install in Linux machines irrespective of flavours.

Before processing with installation process, please download Python tarball  file from official website. if you do not found link, please click here.

Once you got the tarball file, please untar the file by using following command:

$ tar xzf Python-2.7.2.tgz
$ cd python-2.7.2


Before starting installation process, we have configure our Python with system as per our system dependences.
for these, type the following command

$./confure 

By this, Python will configure all the required system dependencies to the machine.

By using 'make' command, we have to compile the source code of Python but it will compile python for /usr/local/ which requires root permission. To install in our selected directory, please follow the following command:

$make altinstall prefix=~/usr/local exec-prefix=~/usr/local

By this command, python source file will be compiled to <home directory>/usr/local folder. at this moment, user may get the following warning which is causing a break point of your installation process




To avoid these "clock skew detected " warnings, simply retype the above "make" command untill you get modified time to 0.00

there is an another process to avoid these kind of warnings.
to remove these warnings, in Linux, we have "touch" command which simply changes the time stamp of the provided file to system time

$ touch <filename>

or else, you can change system date using following command :
$ sudo date <mmddhhmnyyyy>

where mm-month in 01-12 format
          dd-date of the month
          hh-hour of the current time, which should be 24 hours format
          mn-minutes
          yyyy- year

Another way to install property and remove above error is,
Just 'cd' into the directory where the files need a time-stamp update.
             Next use the following command which will update the time-stamps of all the files in the   directory:
      
          $find . -exec touch {} \;

once you have enter this command, it will try to modify entire files time stamp in provided folder. after this, once again run 'make' command. this time it will run successfully without errors warnings.

Ok, till now went good, bu as you already know, every Linux flavor comes with inbuilt python version either 2.5 or 2.6 version of python. if you have installed latest version, by entering 'python ' in terminal, it should launch your python rather than in built python. for these, we need to  link installed python to available python for making a copy for new version

$ ln -s python2.7 python

now, we need to create alias for installed python as follows:

 $alias python = '~/usr/local/bin/python'

now enter python in terminal and see the version. it will give latest version which is installed just now.
to make alias permanent, enter above alias line in .bashrc file and restart the computer for effect of configuration changes.
$vi .bashrc # enter alias in this file