Python super and init explained with example

Python super :

Python super keyword is confusing some time to newbie or even for intermediate python programmers.

But the idea behind super is really simple. In OOP paradigm we often need to do implement inheritance like below:

CODE:

class A(object):

    def fancy_func(self):
        print 'Fancy Function Called from Class A'

class B(A):

    def fancy_func(self):
        return super(B, self).fancy_func()

b is an Object of class B and fancy_func is the method of B, super is returning the base classes method. If we don’t use super,we had declare an object of class A and then we had to call fancy_func. On the other hand,super returns proxy object. Super uses __mro__(method resolution order).

Super can be used:

  • For single inheritance using to refer parent classes
  • In multiple inheritance its very useful in during dynamic execution.

For real life coding when we need to enhance any module method we can easily super to get things done.

And we don’t even have to know details about the base class that we are extending from.

super is only applicable for python new style classes ( the classes derived from object ex. class A(object) )

For python3 the syntax is like below:


super().methoName(args)

Syntax of calling super is like below:

super(subClass, instance).method(args)

Python __init__ :

If you declare a __init__ in your python class, it will be run when you initialize an object from that class.

__init__ acts like constructors in other languages but actually its not. There is a basic major difference between from other methods and __init__,its you cant return anything from it.You can add properties to the current object using like self.myProperty = ‘TEST’ and you can use it in any other method by accessing like self.myProperty

Simply __init__ is used when we want to control the initialization of the class.

Lets build something real with these features:

In the above example we implement both the concept of __init__ and super. Here __init__ using for setting value of url while intilazing the object  and super is being used to call the crawlPyCentral’s getTitles.

To dig more deep into super check this blog post

Advertisements

MongoDB backup script

Last year while I was working in a project, I needed to automate the whole backing up process from taking snapshot of the current db to saving it to AWS S3 buckets. At that time I took most of the staffs from this blog post.

mongo_logo

Couple of days ago, I started to code for making small backup script that will backup to another cloud machine rather than to AWS S3.  Instead of  coding it from scratch, I reused my previously coded script. All I need to implement a bash function(save_in_cloud) which runs a simple scp command 🙂

The whole script look like below:

I reused this script, all I did just added a new function which copy the current backup data to a remote server.  And also updated do_cleanup, now it works in any year.

The backup script depends on other two js (fsync_lock.js and fsync_unlock.js) functions which responsible for locking mongo during  db snapshots and releasing lock  after the  snapshots.

Happy Coding 🙂

Factory pattern in Python

We use design pattern to build reusable solution. Building reusable solution is hard and design patterns helps us by giving common design solution for same sort of problems.

One of the important design patterns is Factory Method Pattern. In Python the implementation of factory pattern look like below:

When to use factory pattern?

There are couple of cases when we can use factory pattern, one of the case is- when there is needed to create objects that are dependent on other objects.

That means when we are going to create a complex objects, and complex objects will be based on other objects. When we need to create the complex object we dont need to know the details about other objects that rely on the creation process. Example is like below:

Ideal situation would be, when we see we are coding to gather information to create objects. And factories help to gather object creation in a single place. And also it helps to create decoupled system.

If you have better understanding and experience of using factory pattern in your python code, please share it in comment.

Django merging two QuerySet using itertools.

I was working with a django application where I need to merge two query set. After going through django ORM docs, could not find anything helpful.

I was planning to do it in a unpythonic way like iterating two queryset and appending each item to a new list, just before doing it I thought it would be better to google for it. And after couple of minutes found it. We can use python itertools to merge two or more query set. Like below:

Python itertools is an amazing module that contains real handy methods what we need to handle iterators and doing different types of operation. If you never used  itertools before you are missing one of the charm of python.

Check Itertools chain docs for details.

Happy Coding!

Comment notification plugin in wordpress

May be it was end of the last year, I was assigned to finish a wordpress project which was taking way too long time to deliver. I was away from wordpress development for more than two years. So after jumping into the project I found most of the user requirements are  bit different than the general.wordpress-logo

One of the requirements was to wordpress admin should be able to use “admin comment” section to reply the comments as email whether the user is subscribed to the post/comment or not. If some one comment into the content and if admin approved it with reply, the user will have to receive an email with the reply.

Worpdress provide a nice action call “comment_post“, I wrote a simple method which will be executed after every comment and check is it approved or not and will send an email. Check the full plugin from github

By the way, without subscriptions into the post and comment, sending email is not “ethical” so if you want to use it use in your own risk.

Also feel free to fork it if you want to add/customize 🙂

Painless deployment with Fabric

Deployment of code in test/staging/production  servers is one of the important part of modern web applications development cycle.

Deploying code were painful because its repetitive same tasks we have to do every time we want to push code, during deployment  if something goes wrong the application will go down too. But the scenario has changed, now we have many tools to make the deployment easier and fun. I have used Capistrano and Fabric for deployment. Found Fabric really painless and as its a Python battery, it was easier for me to adopt and get things done.

I am going to cover fundamental operations and finally a simple fabric script(like boilerplate) for writing your own fabric script.

env = its a Python dictionary like subclass where we define specific settings like password,user etc

local = runs command in  local host(where fabric script is being run)

run = runs command in a remote host

You can use these code tasks in many different ways, to do that check the Fabric Office Documentation from here.

First gist is a sample fabric script,second one is a bash script to install fabric in your ubuntu machine.

 After setting username,password and host information into the script you cab check your server’s access log by running  fab test_server latest_access_log 

I am using fabric for around two years and used for different small,medium and large projects.

There are many interesting open source projects going on top of Fabric. I found these two projects really promising.

1.Fabtools

2.Graphite_fabric

Search through github,you will find many advance level Fabric use.

Happy Coding!

Pythonic way to calculate Standard Deviation

If you are familiar with  basic statistics, I think you know what is Standard Deviation, if you dont know what is Standard Deviation you can check wiki for details.

And if it seems yet hard to wrap the idea into your brain,check this thread. Hope you understand it now. Standard deviation is an efficient when you want to understand a set of data and widely used in different industries. I was working with an algorithm couple of months ago where I had to calculated standard deviation of  a series of data. And the sets of data is large.

After coding couple of versions I code a small python class which calculates standard deviation of data. Check it out

Happy Coding!

Summary of 2012

As its weblog for myself,like every other blogger in the world I share my yearly summary for last couple of years.For 2012 it was …

  • I switched my job,started to work in Tasawr Interactive since last September.
  • Worked with NewsCred API, it was an amazing experience. Coz NewsCred API is a scaled solution and have large code base.I got real taste of working in a complex Python project while I worked with the API team.
  • I had to brush up my Drupal knowledge and learned Drupal 7
  • Started to work on my pet project which is completely based on Python/Django
  • Developed a small financial API for one of my client(I used tastypie for the first time and loved it)
  • Worked for Indexica as a remote developer, where my role was DevOps. I had to develop a portion of their API and also managed cloud infrastructure.
  • Worked with SOLR  and Nutch for the first time and loved both of this.

Daily Unix Commands

If you are a dev or a sys admin  you must rely on unix command to get things done.

These are my daily unix tools list,I am putting these together for myself as a future reference,if it helps anyone else I will be happy 🙂

Screen

I use ‘screen’  for keeping myself alive in my remote cloud machines. If you are new to screen,please check this docs.

Checking list of screen in current machine 'screen -ls'
Resuming 'screen -r screen_name' or 'screen -r pid'
Create new screen 'screen -S screen_name'
Detach from screen using 'ctrl+a+d'
Copy mode start 'ctrl+a+{'
Kill the current window 'ctrl+k'

Screen cheatscheet1 screen cheat sheet2

File Compression

Using zip and unzip

Zip command example is like below:

zip backup.zip filename1 filename2
zip -r backup.zip dir_name

Unzip command example is like below:

unzip backup.zip

tar,gzip and bzip2

tar cfv backup.tar filename1 filename2
tar xvf backup.tar

for specific directory

tar xvf backup.tar -C /dir_name/

to use gzip compression use -z  and for bzip2 compressing use -j like this

for compression:

tar -zcfv backup.tar.gzip filename1
tar -jcfv backup.tbz2 filename

for uncompression

tar -zxvf backup.ta
tar -jxvf  backup.tbz2

Unix file compression cheat sheet

And if you want to learn details about this compression techniques please check this

Vim basics

I use vim for editing files in unix system(specially in remote machines).These are list of commands I use:

Basic Navigation:


j->down
k->up
l->left
r->right
H->first line of the file
G->last line of the file
$->end of the line

Changing Line:


yy->copy the current line
p->paste the copied line

check Vim Cheat sheet .

I rarely use ‘sed’ command,and I only used it for easy find replace of strings(its really handy when you have to work on multiple files for same find replace ).The syntax is like below:

sed s/search_string/replace+string old_file.txt > new_file.txt

check sed refernce