Apr 27, 2015

Iterators and Generators in python

Iterators in python:  Let's start discussion about python iterator with a simple python program involving for loop.
mylist = [1,4,6,7,98]
for x in mylist:
    print x 
Sample output: 1,4,6,7,98

The sample program is self explanatory. Using for loop we are iterating mylist and display its elements. Similarly other basic container types tuple and set can be iterated. Lets understand the
iteration mechanism which python is doing for us.
In Python, the mechanism for iteration is based upon iterator and  iterable.
An iterator is an object that manages an iteration using next() method, here x is a iterator and an iterable is an object that produces an iterator via the syntax iter(obj), mylist is iterable object.

In for loop also, Python has used the next() and iter() method and automated the process to display the elements of list.
Python performs the following two steps:(iterator protocol)
1. Gets an iterator for mylist:
     Call iter(mylist) -> this returns an object with a next() method (or __next__() in Python 3).
2. Uses the iterator to loop over items:
   Keep calling next() method and store the elements in x, until an exception StopIteration is raised
   from within next() which indicate no more element is left to iterated.

What makes mylist iterable?:
  It is iterator protocol which is implemented by mylist(list class).

Along with these basic container types, instance of user defined class can be made iterable by implementing itr() which returns an iterator.An iterator is an object with a next() method.

Generators in python(yield() method): Generators are iterators, but you can only iterate over them once. It's because they do not store all the values in memory, they generate the values on the fly.
A generator function produces a sequence of results instead of a single value. Python uses yield keyword to return generator object.
Note :
1. When a generator function is called first time , it returns an generator object without even 
     beginning execution of the function.
2. When next() method is called for the first time, the function starts executing until it reaches yield
     statement. The yielded value is returned by the next call.
Lets write a sample code  to understand generators in python:Open IDLE and create a file and copy following code line in it. 
def counter(n):
    i = 0
    while i < n:
        yield i
        print "incremented"
        i += 1
  
#call above function and display values using next()
y= counter(3)
print y
print("First call")
print y.next()
print("Second call")
print y.next()
print("Third call")
print y.next()
print("Fourth call")
print y.next()#exception occurred here
Sample output:
-----------------------------------------------------------------
<generator object yrange at 0x02C2B2B0>
First call
0
Second call
incremented
1
Third call
incremented
2
Fourth call
incremented

Traceback (most recent call last):
  File "C:/Python27/test5.py", line 48, in <module>
    print y.next()#exception occured here
StopIteration
-------------------------------------------------------------------
We will execute the above code lines line by line. When function yrange() is executed the very first time, function return a generator object. Display the vale of y in terminal:
>>> y
<generator object yrange at 0x02DDB2B0>  #generator object is returned 
On calling next() the very first time on returned object earlier, runs function yrange() from the beginning until it hits yield and returns initialized value of i,  i.e ,0.
>>> y.next() #First call
0
In second call of y.next(), code lines after yield is executed and value of i is incremented.Again while loop start execution and returns current value of  i when it reaches at yield.
>>> y.next()  #Second call
incremented
1
Similarly,on subsequent call it displays 2 and 3. When fourth time next() is called then StopIteration exception is raised and same is displayed in output. The generator is considered empty once the function runs but does not hit yield any more.

Generator Expressions:-
Generators can be coded succinctly as expressions using a syntax similar to list comprehensions using braces () instead of bracket [] .
[i*i for i in range(10)] is list comprehensions  and (i*i for i in range(10)) is a generator.
Note :
1. generator expressions used as arguments to various functions that consume iterators.
    >>> sum(((x*x for x in range(10)))
    285
2. When there is only one argument to the calling function, the parenthesis around generator 
    expression can be omitted.
    >>> sum(x*x for x in range(10))
    285


Previous : Exception handling in python Next : Object oriented programming in python

Apr 25, 2015

Textual description of firstImageUrl

Method overloading and Operator overloading

Method overloading / constructor (__init__()) overloading : 

Python does not support method overloading.It would be justified to say that , python does not require to support method overloading explicitly as done in other languages like java and c++(varying type of parameters and number of parameters to the functions).
Python is a dynamically typed language so type of parameters of method is decided at execution time and overloading is associated with compile time.That's why in python we write a single constructor (__init__() method) that handles all cases, using either default arguments or type or capability tests.If we want complete freedom of adding more parameters: Python has *args and **kwargs arguments which helps to do so.
  • *args -- tuple of anonymous arguments
  • **kwargs -- dictionary of named arguments
Note:
1.It is not mandatory to call them args and kwargs, that’s just a convention.It’s the * and ** that do the magic.
2. *args and **kwargs can be used both independently and together.

Lets create a class and its multiple instances to understand uses of *args and **kwargs. Open python IDLE and create a file copy following code lines.
import math
class ClassName(object):
    def __init__(self, *argsT, **kwargsD):#*argsV and **kwargsD used instead  
     self.sum = sum(args)
     self.name = kwargs.get('name') #accessing name from dictionary 
     self.address = kwargs.get('address')
Now create two instance of ClassName with different types of arguments.
>>> y = ClassName(1,2,3,4, name='ranjan',address ='Hyderabad')
1,2,3, 4 is of int type passed in *arg tuple and  name='ranjan',address ='Hyde' passed as elements of dictionary **kwargsD. Now display name  and sum from object.
>>> y.name
'ranjan'
>>> y.sum
10
Create second instance with floating type and int type data  and display sum for the same.
>>> y = ClassName(1,2.9,3.0,4,name='nikhil',address ='Hyderabad')
>>> y.sum
10.9

Using *argsT, **kwargsD we can handle need of constructor overloading in python. In some situation when we need independent constructor, factory methods can be used to achieve it, refer this post for more detail.

Method overloading is achieved using default parameters in methods and *args and **kwargs, as we can pass variable number of arguments of different types to a method. Lets write a class to understand how to use parameters with default value in method overloading.
Open python IDLE, create a new file and copy following code.
class Employee(object):
 # __init__ - Constructor of class
 def __init__(self,**kawrgs): 
  self.name = kawrgs.get('name')
  self.employeeId = kawrgs.get('employeeId')
   
 #calculate employee salary method with default values goes here
 def calculateSalary(self, hra =10000, travelExpense = 800 ,
                            hotSkillBonus = 0.0 ,
                            specialAllowance = 25000):
  return hra+travelExpense+hotSkillBonus+specialAllowance
First, we create an object of  Employee class and followed by execute different flavour of calculateSalary().
>>> employee = Employee(name= 'Nikhil', employeeId = '897')
>>> employee.calculateSalary (hra = 12000,hotSkillBonus = 1300)
39100
>>> employee.calculateSalary(hra = 12000,travelExpense = 1200, hotSkillBonus = 1300)
39500
>>> employee.calculateSalary() #No arguments passed, default is used here for all parameters
35800.0

Operator overloading 

In python, built in classes provides natural meaning for many operators. For example, 3+4 perform natural addition and produces 7, [2,4]+[5,6] (Sequence types) perform concatenation and results 
[2, 4, 5, 6]. Now think of , a custom class for which operator(i.e: +) is undefined. It is responsibility of author of that class to provide natural semantics (definition) of that operator to that class using Operator overloading. 
How operator overloading mechanism work ?
For each operator, author has  to implement special method to achieve operator overloading.For example, + operator is overloaded by implementing a method named __add__ , which takes
the right-hand operand as a parameter and returns the result of the expression.
for a + b , call transform to a.__add__(b) , method call on object a. Similarly for multiplication operator (*) , a*b will be converted to a.__mul__(b). 

What will happen when binary operator is applied to two instances of different types ?
Lets say, type1 op type2, in such case python gives preference to first operand of type1 and check whether this class has definition for this operation or not. If definition is not found then it will check with type2 class, whether sufficient definition is available for type2 op type1, if it is found this operation will be performed. However, if no proper definition is found , TypeError exception will be raised. 
Take an example of  2*"Welcome", when we execute this statement in python interpretor, first python check with int class whether it has a proper implementation of  __mul__ which multiply a integer with string.Since, int class does not have such definition, python checks the class definition
for the right-hand operand, in the form of a special method named __rmul__ (i.e., “right multiply”). Since, string class has appropriate definition so __rmul__will be executed and displays 
"WelcomeWelcome" (given string concatenated given no of times ).

Here is the list of operators and special methods to be defined for overloading:
Operator and corresponding special method's


  

Previous: Object oriented programming in python Next:Inheritance in python

Apr 18, 2015

Textual description of firstImageUrl

Object oriented programming in python - Class and Object

Python support object oriented programming paradigm along with procedural programming. Classes and Objects are the two important aspects of object oriented programming. A class creates a new type (analogous to an int class of python) and objects are instances of the class.

Object uses variables to store data called instance variables. variables can also be created in class context, those variables are called Class variables. Variables(fields) and methods are attributes of class.
Along with variables, class also contain methods. In OOP terminology , instance variables are also known as data members and  methods are also
known as member functions.
Class is created using keyword class and fields, methods are added in indented block.A sample class can be created like this.We will see in detail about object included in Employee class while dealing with inheritance in python.
class Employee(object): #object class is mother of all class in python
 # Class variable declaration  
 ......
 # Constructor of class - init() methods
 .......
 # class methods - self identifier  
 ........
self identifier and __init__():- Before going delve into actual class creation, let's understand importance of self and init() in python.
  • It is the self identifier which differentiate class methods from normal python functions. It is mandatory to include self as first parameter list in class methods(member function).self identifies the instance upon which a method is invoked.Please note that, instead of "self" we can use any other name as first parameter in class method, however it is highly recommended to use "self" for the same. When we call any method in object context, we do not pass any thing for self parameter, python handle internally it and pass object reference to it.
  • __init__() method in python serves as constructor as in other language for creating instance of class.When an instance of class is created then python internally execute __int__() method and initialize member fields(instance variables).
Lets create an Employee class with fields - name, employeeId , position and leaveBalance, getters corresponding to these fields and member functions for allocateLeave and sum accumulated corresponding to leave balance.Open Pyhton IDLE and create a new file and copy below sample code in it.
     
class Employee(object):
 '''class variables'''
 _basicSum = 1500
 _allowance = 1000 
 '''Create a new Employee instance with 
    default value of leave balance 0'''
 def __init__ (self, _name,_employeeId, _position):
   self._name = _name
   self._employeeId = _employeeId
   self._position = _position
   self._leaveBalance = 0 #Default value 0
 """getter method for member fields"""
 def get_name(self):
   return self._name
 def get_employeeId(self):
   return self._employeeId
 def get_position(self):
   return self._position
 def get_leaveBalance(self):
   return self._leaveBalance
 '''member function to return sum accumulated  
    corresponding for leave balance'''
 def getTotalSumForLeaveBalance(self):
   return (self._leaveBalance * Employee._basicSum)
   +(Employee._allowance*self._leaveBalance)
 def allocateLeave(self,_leaveBalance):
   self._leaveBalance =  _leaveBalance
Lets walk through the code lines of above class: _basicSum and _allowance are class variables (shared by all instance of class). After that __init__ (self, _name,_employeeId, _position) is defined with first parameter self and other three are instance members. When we create instance of Employee this _init_(...) is executed automatically and member variables are initialized with value passed and default value 0 for _leaveBalance.We have getter method for these member variables and followed by two member function to allocate leave and calculateSum corresponding for leave. We can spot that self is used to access member variables corresponding to the object and class variables is accessed via class name as it is carries in other language  like java. 

Now we will following operation in sequence : 1. create instance of Employee class  2. Allocate leave to new Employee instance. 3.Calculate sum total for leaveBalance.
Create instance of Employee class like this in python terminal :
>>> employee1 = Employee('Nikhil',007,'SSE')   # employee1 reference an instance of Employee
>>> employee2 = Employee('Ranjan',99,'TL')     # employee2 reference an instance of Employee

Allocate leave to both(employee1 and employee2) Employee instance like this: 
.>>> employee1.allocateLeave(12)  # 12 leaves assigned to employee1
>>> employee2.allocateLeave(15)   # 15 leaves assigned to employee2

Calculate sum total for these two instances: 
>>> employee1.getTotalSumForLeaveBalance()  #No value passed for self ,python does it implicitly.
18000
>>> employee2.getTotalSumForLeaveBalance()
22500
Above sequence of events for instance employee1 can be summarized by sequence diagram:

Sequence diagram for creating employee1 instance and calculating sum total
Few point worth noting about class and objects :
  • Every object refers to it’s class via the self.__class__ attribute. So, instead of accessing class variable like Employee._basicSum , we can use self.__class__._basicSum.
  • __class__ is a built-in attribute of every class instance. It is a reference to the class that self is an instance of.
  • All class members (including the data members) are public and all the methods are virtual in Python.
  • Private name mangling: When an identifier in class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class.

Sample example using class and Object:-  



Previous: Iterators and Generators in python Next : Method overloading and Operator overloading

Apr 15, 2015

Textual description of firstImageUrl

Git Commands Recap : Undo commit (Reset and Revert), Difference between Checkout and hard rest

Git Revert: git revert <SHA-of-commit-to-revert>

Suppose we added a piece of code in given commit and we want to remove it from commit. Git revert comes for rescue.
If Git reverts given commit , then Git will make a new commit where that piece of code is deleted. It also works the other way where if piece of code were removed in given commit, then reverting that commit will add that content back.
➜  custom_cloned_repo git:(master) git revert 582d67c9b0a9376101a50d02f46ee34e0de69772
[master fecb359] Revert "created css"
 1 file changed, 0 insertions(+), 0 deletions(-)
 delete mode 100644 front.css

Below image shows, a css file is created and committed. Later we find SHA value using "git log" and revert that commit. In reverting that css file is deleted, git does it by creating new commit. 999999999


Git Reset: git reset <--flag/file/sha>

Reverting creates a new commit that reverts or undos a previous commit. Resetting, on the other hand, erases commits. Three flavour of rest command.
  •  Move HEAD : "reset command" moves the branch that HEAD is pointing to. It means if HEAD is set to the master branch (i.e. We are currently on the master branch), running
    git reset 9e5e6a4 will start by making master point to 9e5e6a4.
    ➜  custom_cloned_repo git:(master) git reset --soft Head~
     Below image shows, we have two branch test and master at two different commit. Once we execute above reset command with flag "--soft", head moves to same commit as test branch.

  • Updating the Index (--mixed) : This is default flag associated with reset, if noting is provided.
    reset with --mixed will bring Head and Index at same commit level.
    ➜  custom_cloned_repo git:(master) git reset HEAD~
    
    OR
    
    ➜  custom_cloned_repo git:(master) git reset --mixed Head~
    
    On executing reset command with --mixed, master and test branch will be on different commit. Index and Head are on same commit. Below image shows master moves back one commit compare to test.

  • Updating the Working Directory (--hard): Think for a sec before using flag "--hard". This flag will overwrite working directory file with the commit to be reset(Head~ in above example).
    After executing --mixed command, master and test branch were on different commit, see first part of below diagram.
    Now we checkout test and use "--hard" flag, css file is deleted from working directory of test branch because Head~ refers to.


Git checkout <branch> vs git reset --hard <branch>

Running git checkout [branch] is pretty similar to running git reset --hard [branch] in that it updates all three trees(Head, Index and working directory) for you to look like [branch], however there are two important differences.

First, unlike reset --hard, checkout is working-directory safe; it will check to make sure it’s not blowing away files that have changes to them. Actually, it’s a bit smarter than that — it tries to do a trivial merge in the Working Directory, so all of the files you haven’t changed will be updated.
reset --hard, on the other hand, will simply replace everything across the board without checking.

The second important difference is how checkout updates HEAD. Whereas reset will move the branch that HEAD points to, checkout will move HEAD itself to point to another branch.

Below image from git-scm.com. Consider master and develop branches which point at different commits and we’re currently on develop (so HEAD points to it). If we run git reset master, develop itself will now point to the same commit that master does. If we instead run git checkout master, develop does not move, HEAD itself does. HEAD will now point to master.
Difference between checkout and reset (Source: git-scm.com)

Ancestry References:

To tell Git about the commit that's one before the current commit or two before the current commit. These are relative references, in git we use special special characters called "Ancestry References" to refer relative references. Those characters are:

^ – indicates the parent commit
~ – indicates the first parent commit

The parent commit – the following indicate the parent commit of the current commit

  • HEAD^
  • HEAD~
  • HEAD~1

The grandparent commit – the following indicate the grandparent commit of the current commit

  • HEAD^^
  • HEAD~2

The great-grandparent commit – the following indicate the great-grandparent commit of the current commit

  • HEAD^^^
  • HEAD~3

The main difference between the ^ and the ~ is evident when a commit is created from a merge. A merge commit has two parents. With a merge commit, the ^ reference is used to indicate the first parent of the commit while ^2 indicates the second parent. The first parent is the branch you were on when you ran git merge while the second parent is the branch that was merged in.


Reference: https://git-scm.com/book/en/v2/Git-Tools-Reset-Demystified

Apr 12, 2015

Singleton with Serialization - What is importance of readresolve in Serialization in Java

Why do we need to make a class serializable ?

When we require an object to convert its state to a byte stream so that the byte stream can be reverted back into a copy of the object then we need to make that class serializable, so that instance of that class can be treated with special

How can we make a class serializable ?

In Java, a object is serializable if its class or any of its superclasses implements either the java.io.Serializable interface or its subinterface, java.io.Externalizable. Serializability of a class is enabled by the class implementing Serializable interface.

java.io.Serializable 
is only a marker interface which tells the Java platform that the object is serializable. Classes that do not implement this interface will not have any of their state serialized or deserialized.

For simplicity, in this post we will use Serializable interface.

What is Singleton class:- Only one instance of this class is created with respect to a given class loader which loads this class in JVM.
If a singleton class is loaded by multiple class loader, multiple instance of this singleton class can be created.  For more details about singleton design pattern refer Singleton Design Pattern.

Below discussion assumes Singleton class is loaded only by one class loader - One object creation allowed for this class.

Main agenda of this post is to analyse -
1. what happens when a singleton class implements serializable interface?
2. How does Singleton design pattern breaks its contarct of creating only one instance ?
3. How to prevent creation of multiple object of Singleton class when it is serializable ?

Lets start with how to make Singleton class with serializable -  by implementing  java.io.Serializable  interface. Below sample code creates singleton class (Bill Pugh Singleton with Holder Pattern) and implements serializable interface.

import java.io.Serializable;

/**
 *
 * @author devinline
 */
public class LazySingleton implements Serializable{
    private static final long serialVersionUID = 1L;
    private LazySingleton() {
    }

    private static class Singleton {

        private static final LazySingleton INSTANCE = 
new LazySingleton();
    }

    public static LazySingleton getInstance() {
        return Singleton.INSTANCE;
    }
    
}

Above Singleton instance is created lazily, only when it is actually used (method getInstance() is called). Inner static class is loaded when INSTANCE references LazySingleton's object.

How many object is created when LazySingleton object is serialized and deserialized ?

Now we will write a client program which uses Singleton object and does serilization and Deserialzation. Below sample program serializes object and compute Hashcode of that object followed by it deserializes stream and retrieves object and compute hashcode for this retrieved object.We notice from sample output is that - Both hashcode is different so both object are different. 

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

/**
 *
 * @author devinline
 */
public class SerializedSingletonClient {

    public static void main(String[] args) throws FileNotFoundException, 
            IOException, ClassNotFoundException {
        LazySingleton singletonInstance = LazySingleton.getInstance();
        //Serialize singleton object
        try (ObjectOutput out = new ObjectOutputStream(new FileOutputStream(
                "file.ser"))) {
            out.writeObject(singletonInstance);
        }
        System.out.println("Serialization stage :singletonInstance hashCode=" + 
                singletonInstance.hashCode());
        
        //Deserialize singleton object
        try (ObjectInput in = new ObjectInputStream(new FileInputStream(
                "file.ser"))) {
            singletonInstance = (LazySingleton) in.readObject();
        }
        System.out.println("Deserialization stage :singletonInstance hashCode=" + 
                singletonInstance.hashCode());

    }
}

Sample output of SerializedSingletonClient 
:- Hashcode is different, two different object created.
Serialization stage :singletonInstance hashCode=332475715
Deserialization stage :singletonInstance hashCode=1940813045

Since our expectation from singleton class is to create one object per classloader. But here two instance is created.

How to prevent creation of multiple object from serializable singleton class ?

Java Serialization provides a special hook in the form of method readResolve() which decides what object is returned by serialization.
In order to achieve that classes must implement this special method readResolve() and when
private method on the class being instantiated, readResolve() is called before returing object and from this method object returned can be overwritten and controlled which object should be returned.

i.e:- Classes that need to define a replacement when an instance of it is read from the stream should implement this special method with the exact signature. (Java Doc)

Below is modified Singleton class which implement readResolve() method. Now we run the singleton client again and we can verify that only object is created with this serialized singleton class from hashcode value.

import java.io.ObjectStreamException;
import java.io.Serializable;

/**
 *
 * @author devinline
 */
public class LazySingleton implements Serializable {

    private static final long serialVersionUID = 1L;

    private LazySingleton() {
    }

    private static class Singleton {

        private static final LazySingleton INSTANCE = 
                new LazySingleton();
    }

    public static LazySingleton getInstance() {
        return Singleton.INSTANCE;
    }
    
    //readresolve returns INSTANCE after deserialization 
    private Object readResolve() throws ObjectStreamException {
        return Singleton.INSTANCE;
    }
}

Sample output of SerializedSingletonClient 
:-  Hashcode value is same, Only one object is created.
Serialization stage : singletonInstance hashCode=348789395
Deserialization stage :singletonInstance hashCode=348789395

-------------- End of post---------------------

Reference :- https://docs.oracle.com/javase/7/docs/api/

Apr 4, 2015

Textual description of firstImageUrl

Exception handling in python - try/except/else/finally

Exceptions are unexpected events that occur during the execution of a program.Consider the following where exception/error occurs:
>>> 10 * (1/0)     #ZeroDivisionError: integer division or modulo by zero
>>> 4 + spam*3  #NameError: name 'spam' is not declared 
>>> '2' + 2     #TypeError: cannot concatenate 'str' and 'int' objects
Here ZeroDivisionError, NameError and TypeError are name of the built-in exception that occurred.Standard exception names are built-in identifiers (not reserved keywords).
1. In Python, exceptions (also known as errors) are objects that are raised (or thrown) by
code that encounters an unexpected circumstance.
2. A raised error may be caught by a surrounding context that “handles” the exception in an appropriate fashion.
3. If Exception occurs and If uncaught, an exception causes the interpreter
to stop executing the program.
Following are list of common exception class found in python:(Image from DSA by Goodrich
Common exception classes in Python

Exception handling/catching in python is carried out using  try .. except statements. Let's take an example to understand try and except statements. Below mentioned code snippet expect user to enter some valid input, however user press "Ctrl+ d" or "Ctrl+c"(KeyboardInterrupt).
try:
    text = raw_input('Enter a valid input --> ')
except EOFError: # Press ctrl + d
    print 'End of file is pressed.'
except KeyboardInterrupt: # Press ctrl + c
    print 'Operation cancelled ..'
else: #if No exception occurred, optional else block is executed 
    print 'You entered {}'.format(text)
Sample output:
>>>
Enter valid input --> # ctrl+c is pressed
Operation cancelled .
>>>
Enter valid input --> test_input
You entered test_input

Notes:- 
1. Normal operational code lines are placed inside try block, as in above example valid user input is
    expected in try block. i.e : Watch for exception in try block.
2. Once exception occurs corresponding except block gets executed.
3. with one try block there can be N number of except block and there has to be at least one except
    clause associated with every try
clause.
4. We can also have an optional else clause associated with a try..except block. The else clause is executed if no exception occurs.
5. If an exception is not caught within the body of the function, the execution of the function
    immediately ceases and the exception is propagated to the calling context.

Exception raising in python is carried out using raise statement with an appropriate instance
of an exception class as an argument. i.e: The error or exception that you can raise should be a class which directly or indirectly must be a derived class of the Exception class. Consider an example to understand how we can raise an exception. Find square root of an number and raise an exception when user input is negative(Square root of a negative number is imaginary value).
Open Python IDLE. Create a new file and copy following codes.
import math
def sqrtC(x):
    if not isinstance(x, (int, float)):
        raise TypeError( "x must be numeric" )
    elif x < 0:
        raise ValueError( "x cannot be negative" )
    else: 
        print 'Square root of number is %f' %math.sqrt( x )

#sqrt(input)
input = int(raw_input("Enter number: "))
try:
    sqrtC(input)
except TypeError:
    print 'TypeError type caught, x is not numeric!!'
except ValueError:
    print 'ValueError type caught, Input is negative!!'
Sample output:
>>>
Enter number: 25
Sqaure root of number is 5.000000
>>>
Enter number: -25
ValueError type caught, Input is negative!!

Lets walk through sample output: When input is 25 , square root 5.00000 is printed and when input is negative number : -25, then ValueError exception is raised and caught in calling context. 

Notes :- 
 Python support user defined exception.Exceptions should typically be derived from the Exception class, either directly or indirectly. Click here to know how to create user defined exception.

Clean-up actions in python is achieved using try...finally. A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.When an exception has occurred in the try clause and has not been handled by an except clause (or it has occurred in a except or else clause), it is re-raised after the finally clause has been executed. Let's write a sample code to understand use of finally with try statement.
def divide(x, y):
  try:
      result = x / y
  except ZeroDivisionError:
      print "division by zero!"
  else:
      print "result is", result
  finally:
      print "executing finally clause"

divide(12,0)
divide("12","2") #No 'TypeError' exception caught in this case.
Sample output:  On executing divide(12,0 ), finally block is executed after exception ZeroDivisionError is caught.
>>>
division by zero!
executing finally clause
While when divide("12","2" ) is executed, finally block is executed before the exception is re-raised and thrown on console.
>>>
executing finally clause
Traceback (most recent call last):
  File "C:/Python27/clean_finally.py", line 11, in <module>
    divide1("2", "1")
  File "C:/Python27/clean_finally.py", line 3, in divide1
    result = x / y
TypeError: unsupported operand type(s) for /: 'str' and 'str'

Predefined Clean-up Actions in python is done using with statement. With statement guarantee that resources are closed and placed in pool right after its use, even if execution is failed.In the following code lines, after the statement is executed, the file f is always closed, even if a problem was encountered while processing the lines.
with open("myfile.txt") as f:
    for line in f:
        print line,
Previous:Python input and output  Next:Iterators and Generators