Python’s global keyword allows to modify the variable which is out of current scope.
In [13]: bar = 1 In [14]: def foo(): ....: global bar ....: bar = 2 ....: In [15]: bar Out[15]: 1 In [16]: foo() In [17]: bar Out[17]: 2 In the above example, bar was declared before foo function. global bar refers to the bar variablewhich is outside the foo scope. After foo invocation bar value was modified inside foo.
[Read More]
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]
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]
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]
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]
introduction to python
This is the material which I use for teaching python to beginners.
tld;dr: Very minimal explanation more code.
Python?
Interpreted language Multiparadigm Introduction
hasgeek@hasgeek-MacBook:~/codes/python/hacknight$ python Python 2.7.3 (default, Aug 1 2012, 05:14:39) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> print "Let's learn Python" Let's learn Python Numbers
>>> 23 + 43 66 >>> 23 - 45 -22 >>> 23 * 45 1035 >>> 23 ** 4 279841 >>> 23 / 4 5 >>> 23 / 4.
[Read More]
Deploying full fledged flask app in production
This article will focus on deploying flask app starting from scratch like creating separate linux user, installating database, web server. Web server will be nginx, database will be postgres, python 2.7 middleware will be uwsgi, server ubuntu 13.10 x64. Flask app name is fido. Demo is carried out in Digital ocean.
Step 1 - Installation Python header
root@fido:~# apt-get install -y build-essential python-dev Install uwsgi dependencies
root@fido:~# apt-get install -y libxml2-dev libxslt1-dev Nginx, uwsgi
[Read More]