Python Tutorial

Wednesday, February 20, 2013

Python object-class property

Python object-class property example code
class MyClass(object):
        def __init__(self, first_name, last_name):
                self.first_name = first_name
                self.last_name = last_name
        @property
        def name(self):
                return self.first_name +" "+ self.last_name


myClass = MyClass("Abu", "Zahed")
print myClass.name

Output:

Abu Zahed

date compare - code snippet

import datetime

a = datetime.date(2012,1,31) # YYYY, MM, DD
b = datetime.date(2009,10,31) # YYYY, MM, DD

print a == b
print a > b
print a < b


Output:
False
True
False

Tuesday, February 19, 2013

Python isinstance example

Python check an object instance using isinstance method.

class MyClass(object):
    pass

a = MyClass()
print isinstance(a,MyClass)

a = 5
print isinstance(a,MyClass)


Output:
True
False

Decorator in python

Python decorator example : Validate a function argument using decorator.


All source code available on github
from functools import wraps

def validate(func):
    @wraps(func)
    def wrapper(*args):
        for num in args:
            try:
                int(num)
            except:
                return None
        return func(*args)

    return wrapper

@validate
def add_num(*args):
    total = 0
    for num in args:
        total += num
    return total


print add_num(1,2,3)
print add_num(1,2,"asd")
print add_num(1,2,None)


Output:
6
None
None

Python implement caching - using decorator

Python custom caching using decorator.

All source code available on github

from functools import wraps

def custom_memoize(func):
    cache = {}
    @wraps(func)
    def wrapper(*args):
        if args in cache:
            print "Returning cache data"
            return cache[args]
        # If result not found then call the function
        result = func(*args)
        cache[args] = result
        return result

    return wrapper

@custom_memoize
def add(x,y):
    return x+y

print add(1,2)
print add(2,5)
print add(1,2)
print add(2,5)

Output:
3
7
Returning cache data
3
Returning cache data
7

Closure in python

Closure is a function that defined inside another function. Closure function can be return outside, then other code can use it. Example given below:

All source code available on github

def value(x):
    def increment_by(y):
        return x+y
    return increment_by

increment10 = value(10)
print increment10(5)

increment45 = value(45)
print increment45(5)


Output:
15
50

Python collections - Counter

Counter is used for counting hashable object.

All source code available on github

from collections import Counter

a=[1,2,3,4,2,3,4,45,4,7,8]
counter = Counter(a)

print counter
print counter.values()
print counter.keys()


Output:
Counter({4: 3, 2: 2, 3: 2, 1: 1, 7: 1, 8: 1, 45: 1})
[1, 2, 2, 3, 1, 1, 1]
[1, 2, 3, 4, 7, 8, 45]

Python collections - deque

Deque is another powerful data structure from collections. It implements all feature of Double-ended_queue.Lets see an example how to use it.


All source code available on github

from collections import deque

dq = deque([1,2,3])
print dq

dq.append(4) # add end of the deque
dq.appendleft(5) # add beginning of the deque

print dq

print dq.pop()
print dq.popleft()
print dq

dq.extend([22,33,44]) # add multiple element to end of existing deque
dq.extendleft([444,333]) # add multiple element to beginning of existing deque
print dq

print 22 in dq # search in deque

dq.rotate(1)
print "Right rotate:",dq
dq.rotate(-1)
print "Left rotate:",dq

Output:
deque([1, 2, 3])
deque([5, 1, 2, 3, 4])
4
5
deque([1, 2, 3])
deque([333, 444, 1, 2, 3, 22, 33, 44])
True
Right rotate: deque([44, 333, 444, 1, 2, 3, 22, 33])
Left rotate: deque([333, 444, 1, 2, 3, 22, 33, 44])

Python collections - OrderedDict

OrderDict remembers its insertion order. If a new entry overwrites an existing entry, the original insertion position is left unchanged. Deleting an entry and reinserting it will move it to the end.


All source code available on github

from collections import OrderedDict
d = OrderedDict()

d[3]=5
d[1]=6
d[20]=9
d["cse"]=77

print d

del d[1]
d[1] = 123

print d
print d[1]
print d["cse"]

Output:
OrderedDict([(3, 5), (1, 6), (20, 9), ('cse', 77)])
OrderedDict([(3, 5), (20, 9), ('cse', 77), (1, 123)])
123
77

Python collections - namedtuple

collections.namedtuple is a factory function for creating tuple subclasses with named fields. It can be used as struct or data container.

All source code available on github

from collections import namedtuple

Point = namedtuple('Point', ['x' ,'y'])

p1=Point(1, 2)
p2=Point(6, 4)

print p1
print p2
print "p1[0]",p1[0],"p1[1]",p1[1]
print "p2.x",p2.x,"p2.y",p2.y

Output:
Point(x=1, y=2)
Point(x=6, y=4)
p1[0] 1 p1[1] 2
p2.x 6 p2.y 4

Monday, February 18, 2013

Code snippet: Array initilize by odd number

a=[i for i in range(0,20) if i%2]
print a

Output:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Python exceptions



All source code available on github

try:
    v = 1/0
except ZeroDivisionError:
    print "Divide by zero"

try:
    v = "CSE"
    int(v)
except ValueError:
    print "Value error"

try:
    raise Exception("Exception info")
except Exception as data:
    print data.args


Output:
Divide by zero
Value error
('Exception info',)

File read code snippet



All source code available on github

import sys

def readFile(filename):
    try:
        file = open(filename,'r')
        content = file.read()
        file.close()
        return content
    except IOError:
        print "IOError:",IOError.args[0]
    except :
        print "Unexpected error:",sys.exc_info()[0]
        raise

Keyword arguments

For keyword arguments we need to use two asterisks (**) before the argument name.


All source code available on github

def addValue(**kwargs):
    total = 0
    for key, value in kwargs.items():
        print "Key",key,"value",value
        total += value
    return total


print "Total",addValue(item1=2, item2=3 ,item3=5, item4=7)

Output:
Key item2 value 3
Key item3 value 5
Key item1 value 2
Key item4 value 7
17