Tutorials in ‘Python’ Category

Using *args and **kwargs in Python

Python provides a special syntax for function definitions to allow the usage of variable length argument lists. The syntax is the so called *args and **kwargs. Basically the argument preceded with a single asterisk (not necessarily called args) is used for passing the so called non-keyworded argument list, while the double asterisk is used to pass the keyworded argument list. But let’s show all that in a few examples, shall we?

The following code:

def var_args_function(a, b, *args):
    print('a =', a)
    print('b =', b)
    for i in args:
    print('extra arg =', i)

var_args_function(1, 2, 'arg1', -2, 'three', 'last_one')

Results in this output:

a = 1
b = 2
extra arg = arg1
extra arg = -2
extra arg = three
extra arg = last_one

In the example, our function is passed two normal (or so called positional) arguments and four more arguments, all of which are contained in the args variable. The args variable is actually a tuple, and as any tuple it can be iterated, indexed, etc.

Now what about kwargs?

def var_kwargs_function(a, **kwargs):
    print('a =', a)
    for i in kwargs:
        print('kwargs[%s] = %s' % (i, kwargs[i]))

var_kwargs_function(2, var1=1, var2='two', var3='three')

Results in:

a = 2
kwargs[var1] = 1
kwargs[var3] = three
kwargs[var2] = two

But what is kwargs? It is actually a dict and you can do with it anything you do to a normal dict (yes, including changing it, although that is considered bad practice).

A word about order of the arguments – there are two rules you must follow – non-keworded arguments before keworded and formal arguments before argument lists.

For example:

def f(a, b, c, *args, **kwargs) is OK


def f(*args, a, **kwargs, b, c) is NOT OK

A word about positioning of default arguments – consider these two functions:

def f(a, *args, b=17):
    print('Function f got', a, args, b)

def g(a, b=17, *args):
    print('Function g got', a, args, b)

The following calls:


Result in the following:

Function f got 2 (3, 4, 5) 17
Function f got 2 (3, 4, 5) 8
Function g got 2 (4, 5) 3
Traceback (most recent call last):
File "<pyshell#66>", line 1, in <module>
TypeError: g() got multiple values for keyword argument 'b'

Let’s finish with calling a function with args and kwargs:

def var_args_n_kwargs_f(a, *args, **kwargs):
    print('a =', a)
    for i in args:
        print('extra arg =', i)
    for i in kwargs:
        print('kwargs[%s] = %s' %(i, kwargs[i]))

args = (-1, -2, -3, 'onearg')
kwargs = {'key1': 'val1', 'key2': 'val2', 'last_key': 'last_val'}

var_args_n_kwargs_f(13, *args, **kwargs)

Will result in:

a = 13
extra arg = -1
extra arg = -2
extra arg = -3
extra arg = onearg
kwargs[key2] = val2
kwargs[key1] = val1
kwargs[last_key] = last_val

Note: You can pass anything that can be casted to tuple as args and

VN:F [1.9.18_1163]
Rating: 6.3/10 (3 votes cast)

Run cron jobs within Django using django-cron

Quite often web applications require cron-like behavior which more or less contradicts with the request-response model.

Not many host providers allow users to create a cron jobs, and even if it is possible, if your site relies on an external script it loses its integrity. It no longer is a website, it is a website relying on cron jobs.

Now at first glance, there is not much difference, but such things make migrating harder and/or may cause a lot of problems in the long run.

As we all know Django is an open source web application framework, designed for rapid development. It follows the so called DRY principle and therefore greatly emphasizes on “pluggability”. In this short tutorial we will show you how to “plug-in” a little but very useful Django application called django-cron, which allows you to easily get cron line behavior.

You can visit the project’s site in at http://code.google.com/p/django-cron

Installation is fairly easy:

  • Download the source
  • Place django_cron on your python path
  • Add “django_cron” in the list of installed apps in your settings.py:
  • In the beginning of your global urls.py file add:
import django_cron
  • Write your crons in a file named cron.py inside the application you want write crons to. Note: The application must be installed in your settings.py

A cron job is fairly easy to write.

Here is an example cron.py file which deletes old files from a fixed directory:

import os
import time
from django_cron import cronScheduler, Job

class DeleteOldFilesCron(Job):
“””A cron which deletes files older than a minute from a fixed directory”””

    run_every = 60*60*24 # run every day

    def job(self):
        path = ‘/var/www/html/media/tmp/’
        files = os.listdir(path)
        for file in files:
            if(time.time() – os.path.getmtime(path + file) > 60):
                os.remove(path + file)


Naturally you can have several crons in your cron.py

Note: There are some Apache specific configurations which must be taken into account. For more information visit http://code.google.com/p/django-cron/wiki/Install

VN:F [1.9.18_1163]
Rating: 3.0/10 (2 votes cast)

How to create an executable file (.exe) from Python script

Python is a general-purpose high-level programming language, which combines clear syntax and extreme power. It is a multi-paradigm programming language, which is often used as a scripting language, but can also be used in other contexts. There are various GUI modules for Python so one can make a really complex application. Creating an executable file from a Python script is a good idea for many reasons. For example, it makes you application easier to distribute since the end user does not need to have Python installed.
To start you must have the following installed:

Python – you can download it from http://www.python.org/
py2.exe – downloadable from http://www.py2exe.org Read the rest of this entry »

VN:F [1.9.18_1163]
Rating: 10.0/10 (1 vote cast)