python source fileencoding

Some of the python source file starts with -*- coding: utf-8 -*-. This particular linetells python interpreter all the content (byte string) is utf-8 encoded. Lets see how it affects the code. uni1.py: # -*- coding: utf-8 -*- print("welcome") print("animé") output: ➜ code$ python2 uni1.py welcome animé Third line had a accented character and it wasn’t explictly stated as unicode. print function passed successfully.Since first line instructed interpreter all the sequences from here on will follow utf-8, so it worked. [Read More]

How to install externally hosted files using pip

As of writing (12, May 2014) latest version of pip is 1.5.1. pip doesn’tallow installing packages from non PyPI based url.It is possible to upload tar or zip or tar.gz file to PyPI or specifydownload url which points other sites(Example: pyPdf points to http://pybrary.net/pyPdf/pyPdf-1.13.tar.gz).pip considers externally hosted packages as insecure. Agreed. This is one of the reason why I kept using pip 1.4.1. Finally decided to fix this issue.Below is the sample error which pip throws. [Read More]
python  pip 

Bus journey

I am big fan of bus travel. Still it is my only mode of transportation. The two reason I love it are wind and sight seeing. Whenever the wind kisses me I forget myself and start thinking about memories. The best part of the wind (Thendral) is it kindles happiness, sad moments, memorable ones, wishes and missing. Thendral has complete effect of changing my mood and mode. I don’t think only thendral has this effect. [Read More]
bus  wind 

How to learn Python ?

Over period of time few people have asked me in meetups, online I want to learn python. Suggest me few ways to learn. Everyone who asked me had differentbackground and different intentions. Before answering the question I try to collectmore information about their interest and their previous approaches. Some learnt basicsfrom codecademy, some attended beginners session in Bangpypers meetup. In this postI will cover general questions asked and my suggested approach. [Read More]

Stop iteration when condition is meet while iterating

We are writing a small utility function called is_valid_mime_type. The function takes a mime_typeas an argument and checks if the mime type is one of the allowed types. Code looks like ALLOWED_MIME_TYPE = ('application/json', 'text/plain', 'text/html') def is_valid_mimetype(mime_type): """Returns True or False. :param mime_type string or unicode: HTTP header mime type """ for item in ALLOWED_MIME_TYPE: if mime_type.startswith(item): return True return False Above code can refactored into single line using any. [Read More]
python  any  next 

Best weekend in recent times

Normally I don’t plan weekends. I code, watch movies. This weekend (8th March) was different though. March 7th, friday evening wasn’t good. I was banging my head at work to get api working. Then came back home. Relaxed for an hour Facebook, Youtube. Then opened emacs and started to play Raja sir’s music. Stared at code, walked along the execution. Figured out the issue. Can’t ask for more. Calm and code. [Read More]

Find n largest and smallest number in an iterable

Python has sorted function which sorts iterable in ascending or descending order. # Sort descending In [95]: sorted([1, 2, 3, 4], reverse=True) Out[95]: [4, 3, 2, 1] # Sort ascending In [96]: sorted([1, 2, 3, 4], reverse=False) Out[96]: [1, 2, 3, 4] sorted(iterable, reverse=True)[:n] will yield first n largest numbers. There is an alternate way. Python has heapq which implements heap datastructure. heapq has function nlargest and nsmallest which take arguments n number of elements, iterable like list, dict, tuple, generator and optional argument key. [Read More]

Counting elements with dictionary

Let’s say you want to find how many times each element is present in the list or tuple. Normal approach words = ['a', 'the', 'an', 'a', 'an', 'the'] d = {} for word in words: if word in d: d[word] += 1 else: d[word] = 1 print d {'a': 2, 'the': 2, 'an': 2} Better approach words = ['a', 'the', 'an', 'a', 'an', 'the'] d = {} for word in words: d[word] = d. [Read More]

Two scoops of django

Two Scoops of Django -1.5 is book by Pydanny and Audrey Roy focusing on writing clean and better Django application. If you are using Django in production this is must read book. Q: I am using django since 0.8 do I need this book ? A: Yes, consider the book as starting point to validate your assumption. Q: I just started using django, should I read this ? A: Yes. I started to use django in production last month. [Read More]

Updating model instance attribute in django

It is very common to update single attribute of a model instance (say update first name in user profile) and save it to db. In [18]: u = User.objects.get(id=1) In [19]: u.first_name = u"kracekumar" In [20]: u.save() Very straight forward approach. How does django send the sql query to database ? In [22]: from django.db import connection In [22]: connection.queries Out[22]: [... {u'sql': u'UPDATE "auth_user" SET "password" = \'pbkdf2_sha256$12000$vsHWOlo1ZhZg$DrC46wq+a2jEtEzxmUEw4vQw8oV/rxEK7zVi30QLGF4=\', "last_login" = \'2014-02-01 06:55:44. [Read More]