Tuesday, December 14, 2010

Comparison of Oracle, MySQL and Postgres DBMS


Comparison are given below with include all the basic concept :-
Category Problem Assessment
MySQL Oracle8 Postgres
Elementary features Basic data types B C A
SQL C B B
Declarative constraints C A A
Programming abstractions D A C
Generation of ids C A A
National chars B A B
Transactions Transactions D A A
Locks D A A
Multiuser access C A C
Programming in DB

Sunday, November 28, 2010

TMUX – The Terminal Multiplexer

tmux is similar to screen as it lets you run numerous TTY’s in the same terminal window. It enables a number of terminals to becreated, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background, then later reattached.
Usecommand for attach after detached to reattached.
$ tmux attach

When tmux is started it creates a new session with a single window and displays it on screen. A status line at the bottom of the screen shows information on the current session and is used to enter interactive
commands.

Thursday, November 18, 2010

Sphinx Auto genrate documentation for Django Project

 
Sphinx is a tool that makes it easy to create intelligent and beautiful documentation.

Installing your doc directory

python -c 'import sphinx'
If that fails grab the latest version of and install it with:
> sudo easy_install sphinx
Now you are ready to build a template for your docs, using sphinx-quickstart:
> sphinx-quickstart
accepting most of the defaults. I choose “sampledoc” as the name of my project. cd into your new directory and check the contents:
home:~/tmp/sampledoc> ls
Makefile      _static         conf.py
_build                _templates      index.rst

The index.rst is the master ReST for your project, but before adding anything, let’s see if we can build some html:
make html
If you now point your browser to _build/html/index.html, you should see a basic sphinx site.

Monday, October 25, 2010

Django-Cms Installation error "PageAdmin.exclude' refers to field 'created_by' that is missing from"


Error :
Error "ImproperlyConfigured at / 'PageAdmin.exclude' refers to field 'created_by' that is 
missing from the form" 
Problem Solve :
Fixed this error 
by just setting editable=False on created_by and changed_by and removing all fields from 
PageAdmin.exclude (the other fields already were editable=False)
Edit two files to fix this error
 
Edit file: cms/admin/pageadmin.py
Line no. 65 approximately. 
 revision_form_template = "admin/cms/page/revision_form.html"
Change this line
-    exclude = ['created_by', 'changed_by', 'lft', 'rght', 
'tree_id', 'level']
by 
+  exclude = []  
 mandatory_placeholders = ('title', 'slug', 'parent', 'site',  
'meta_description', 'meta_keywords', 'page_title', 'menu_title') 
top_fields = [] 
 general_fields = ['title', 'slug', ('published', 'in_navigation')]
 

Monday, September 20, 2010

Python : Virtual Python Environment builder

Virtual Python Environment builder
virtualenv is a tool to create isolated Python environments.
The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.4/site-packages (or whatever your platform's standard location is), it's easy to end up in a situation where you unintentionally upgrade an application that shouldn't be upgraded.
Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.
Also, what if you can't install packages into the global site-packages directory? For instance, on a shared host.
In all these cases, virtualenv can help you. It creates an environment that has its own installation directories, that doesn't share libraries with other virtualenv environments (and optionally doesn't use the globally installed libraries either).

The basic usage is:
$ python virtualenv.py ENV

Friday, September 10, 2010

Django : FileField() or ImageField()

In Django its very simple to handle images and file field.

First you define the ImageField and FileField in Class.
for example :
Class File(models.Model):
image =models.ImageField(upload_to = 'path')
File =models.FileField(upload_to = 'path')

Using a FileField or an ImageField in a model takes a few steps:
  1. In your settings file, you'll need to define MEDIA_ROOT as the full path to a directory where you'd like Django to store uploaded files. (For performance, these files are not stored in the database.) Define MEDIA_URL as the base public URL of that directory. For Example :MEDIA_ROOT = "/media/"  , MEDIA_URL = 'http://localhost/media/'
  2. Add the FileField or ImageField to your model, making sure to define the upload_to option to tell Django to which subdirectory of MEDIA_ROOT it should upload files.
  3. All that will be stored in your database is a path to the file (relative to MEDIA_ROOT). You'll most likely want to use the convenience url attribute provided by Django. For example, if your ImageField is called file, you can get the absolute URL to your image in a template with {{ object.file.url }}.

Saturday, September 4, 2010

Django application : Contact form

Make the Contact form in django and also mail is send to admin .

forms.py
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
email = forms.EmailField(required=False, label='Your e-mail address')
message = forms.CharField(widget=forms.Textarea)

View.py
from django.core.mail import send_mail
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from mysite.contact.forms import *
from django.template import RequestContext
from django.core.urlresolvers import reverse

Django application : Add two number using forms

In Django its very simple to use the Django forms and create a very simple application using django forms.
Example: Add to number using Djnago forms
forms.py
from django import forms
class Output(forms.Form):
input1 = forms.FloatField()
input2 = forms.FloatField()

Script :Find and Replace word from files.

Script for Replace the One word with another word from all files place in present directory.

And also take backup of old files.

Step to use :
> Copy the below script in file
> Change the permission of file $chmod u+x filename
> Run this ./filename
> FindWord is word to find and replace With ReplaceWord
{
for fl in *.php; do
mv $fl $fl.old
sed 's/FindWord::/ReplaceWord::/g' $fl.old > $fl
done
}

Saturday, August 28, 2010

Django Application : Create blog

Django : A Simple Blog Example

  First Create application in Django project directory
#python manage.py startapp blog
 Edit your setting.py file and add appilcation code 
For example :-
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'mysite.blog',  
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
)
also add  Email host to send email.
by default its for locahost, but if your host have not configure EMAIL_HOST then you add this in settings.py 

#EMAIL_HOST = "hostname.com"

 Edit Urls in url.py main file in  project Directory.
Urls.py 
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
(r'^blog/', include('mysite.blog.urls')),
)

Saturday, August 14, 2010

Automation Project is approved : Sourceforge.org And Sarovar.org

Project registration for Automation has been approved.
Sarovar
links:-
http://sarovar.org/projects/automation/
http://automation.sarovar.org/
Sourceforge
links:-
http://automations.sourceforge.net/
http://sourceforge.net/projects/automations/

Tuesday, August 10, 2010

Check Django version

Start the interactive Python interpreter
>>> import django


>>> print django.VERSION

Monday, August 9, 2010

Batch resize/Compress all images in a folder.

Make a new file (not as root):
Run In Terminal
#gedit ~/.gnome2/nautilus-scripts/batch640x480

and then Add
#!/bin/sh 
# Use this script to batch resize all images in a folder. 
# First open the folder and then use the script.  
for file in `ls -l` 
do 
name=`echo $file | cut -f1 -d.`
convert -geometry 680x500 -quality 65 $file ${name}_680x500.jpg
done


Save this file and make this file executable:
#chmod +x ~/.gnome2/nautilus-scripts/batch640x480
Go to the folder you'd like to resize. Then rightclick and find the 'batch640x480' script.
I use this script for resizing large amounts of photo's for a website

Sunday, August 8, 2010

Drupal error : Function ereg() is deprecated

Its is very simple to solve
open file includes/file.inc in drupal directory
Goto line no in which this error is show


where you can see something like this
elseif ($depth >= $min_depth && ereg($mask, $file))
Now add @ sign before ereg($mask, $file)
copy below line past this line
elseif ($depth >= $min_depth && @ereg($mask, $file))

Its works

Thursday, August 5, 2010

Python : CMS

Plone

A powerful, flexible Content Management solution that is easy to install, use and extend

Plone lets non-technical people create and maintain information for a public website or an intranet using only a web browser. Plone is easy to understand and use — allowing users to be productive in just half an hour — yet offers a wealth of community-developed add-ons and extensibility to keep meeting your needs for years to come.

Click here for further detail

Skeletonz


Skeletonz is a new content management system (CMS) based on Python. It differs from others by being simple, but yet very powerful and extensible. If you need a simple system that you and your users are going love then Skeletonz might be the solution you are looking for! The system is open source and released under GNU GPL.

Click here for further detail

Wednesday, August 4, 2010

Django : Auto-Generate model.py file from PostgreSQL / MySQL / SQLite database

inspectdb

django-admin.py inspectdb
Introspects the database tables in the database pointed-to by the NAME setting and outputs a Django model module (a models.py file) to standard output.
This feature is meant as a shortcut, not as definitive model generation. After you run it, you'll want to look over the generated models yourself to make customizations. In particular, you'll need to rearrange models' order, so that models that refer to other models are ordered properly.
Primary keys are automatically introspected for PostgreSQL, MySQL and SQLite, in which case Django puts in the primary_key=True where needed.
inspectdb works with PostgreSQL, MySQL and SQLite. Foreign-key detection only works in PostgreSQL and with certain types of MySQL tables.
Example :
Use command
#python manage.py inspectdb >>Models.py
this will automatically convert the django database into Models.py file .

Saturday, July 31, 2010

Python : Accesssing a MySQL Database

The MySQLdb module makes this task extremely easy:
import MySQLdb

# Create a connection object, then use it to create a cursor
Con = MySQLdb.connect(host="127.0.0.1", port=3306, 
    user="joe", passwd="egf42", db="tst")
Cursor = Con.cursor(  )

# Execute an SQL string
sql = "SELECT * FROM Users"
Cursor.execute(sql)

# Fetch all results from the cursor into a sequence and close the connection
Results = Cursor.fetchall(  )
Con.close(  )
Youcan get the MySQLdb module from http://sourceforge.net/projects/mysql-python. It is a plain and simple implementation of the Python DB API 2.0 that is suitable for all Python versions from 1.5.2 to2.2.1 and MySQL Versions 3.22 to 4.0.

Sunday, July 25, 2010

Python : Errors and Exceptions

Until now error messages haven’t been more than mentioned, but if you have tried out the examples you have probably seen some. There are (at least) two distinguishable kinds of errors: syntax errors and exceptions.

Syntax Errors

Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while you are still learning Python:
>>> while True print 'Hello world'
  File "<stdin>", line 1, in ?
    while True print 'Hello world'
                   ^
SyntaxError: invalid syntax
he parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected. The error is caused by (or at least detected at) the token preceding the arrow: in the example, the error is detected at the keyword print, since a colon (':') is missing before it. File name and line number are printed so you know where to look in case the input came from a script.

Python : Input and Output

Fancier Output Formatting

So far we’ve encountered two ways of writing values: expression statements and the print statement. (A third way is using the write() method of file objects; the standard output file can be referenced as sys.stdout
Luckily, Python has ways to convert any value to a string: pass it to the repr() or str() functions.
The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter (or will force a SyntaxError if there is not equivalent syntax). For objects which don’t have a particular representation for human consumption, str() will return the same value as repr(). Many values, such as numbers or structures like lists and dictionaries, have the same representation using either function. Strings and floating point numbers, in particular, have two distinct representations.
Some examples:
>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1.0/7.0)
'0.142857142857'
>>> repr(1.0/7.0)
'0.14285714285714285'

Friday, July 23, 2010

PHP String Functions

explode


Description :

array explode ( string $delimiter , string $string [, int $limit ] )

Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.   
 Examples  explode() 
<?php
// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2

// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *

?>

Tuesday, July 20, 2010

Work Shop at Drishti School, Ludhiana

In Drishti School, Near Ludhiana, we  give a Workshop . It was very interesting to teach little children and their teachers Linux Softwares and to solve their problems. We are six students with Dr. H.S Rai. Drishti School has bought 40 Linux based Tablet-PC which has default ubuntu 8.10 installed on them. we all gave presentations on different things.



I have given my presentation on KGeography  for kids.
KGeography is a Free and open source educational software game that tests students geographical knowledge
Besides for educational purposes, KGeography can be used for evaluating ones knowledge. Right now it has five games:


Sunday, July 18, 2010

Display an image from a MySQL database in a web page via PHP

Here's a sample HTML page we're going to include an image in:

<html>
<head>
<title>Demo of Database Image in a page</title>
</head>
<body>
Here is your picture:<br>
<img src=picscript.php?imname=potwoods><br>
Example by Well House Consultants
</body>
</html>


Then you need the PHP script - called picscript.php in the same directory in my example:

<?php
mysql_connect("localhost","wellho","xxxxxxx");
mysql_select_db("wellho");
$image = stripslashes($_REQUEST[imname]);
$rs = mysql_query("select * from im_library where filename=\"".
addslashes($image).".jpg\"");
$row = mysql_fetch_assoc($rs);
$imagebytes = $row[imgdata];
header("Content-type: image/jpeg");
print $imagebytes;
?>

Monday, July 12, 2010

Basic Guide lines for python coding

For Python, has emerged as the style guide that most projects adhere to; it promotes a very readable and eye-pleasing coding style. Every Python developer should read it at some point; here are the most important points extracted for you:

  • Use 4-space indentation, and no tabs.
    4 spaces are a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read). Tabs introduce confusion, and are best left out.
  • Wrap lines so that they don’t exceed 79 characters.
    This helps users with small displays and makes it possible to have several code files side-by-side on larger displays.
  • Use blank lines to separate functions and classes, and larger blocks of code inside functions.
  • When possible, put comments on a line of their own.
  • Use docstrings.
  • Use spaces around operators and after commas, but not directly inside bracketing constructs: a = f(1, 2) + g(3, 4).
  • Name your classes and functions consistently; the convention is to use CamelCase for classes and lower_case_with_underscores for functions and methods. Always use self as the name for the first method argument .
  • Don’t use fancy encodings if your code is meant to be used in international environments. Plain ASCII works best in any case.

Sunday, July 11, 2010

PHP function for PostGreSQL database

pg_connect() opens a connection to a PostgreSQL database specified by the connection_string.
If a second call is made to pg_connect() with the same connection_string as an existing connection, the existing connection will be returned unless you pass PGSQL_CONNECT_FORCE_NEW as connect_type.


The old syntax with multiple parameters $conn = pg_connect("host", "port", "options", "tty", "dbname") has been deprecated.

For example :-
$con = pg_connect("host=$dbhost user=$dbuser password=$dbpasswd dbname=$dbname" )

pg_close() closes the non-persistent connection to a PostgreSQL database associated with the given connection resource.
For example :-
pg_close($con);

pg_connection_status() returns the status of the specified connection.

For example :-
<?php
  $dbconn = pg_connect("dbname=publisher") or die("Could not connect");
  $stat = pg_connection_status($dbconn);
  if ($stat === PGSQL_CONNECTION_OK) {
      echo 'Connection status ok';
  } else {
      echo 'Connection status bad';
  }  
?>

pg_fetch_all() returns an array that contains all rows (records) in the result resource.

For example :-
$arr = pg_fetch_all($result);

print_r($arr);
pg_fetch_result() returns the value of a particular row and field (column) in a PostgreSQL result resource.

<?php
$db = pg_connect("dbname=users user=me") || die();

$res = pg_query($db, "SELECT 1 UNION ALL SELECT 2");

$val = pg_fetch_result($res, 1, 0);

echo "First field in the second row is: ", $val, "\n";
?>
pg_fetch_array() returns an array that corresponds to the fetched row (record).
pg_fetch_array() is an extended version of pg_fetch_row(). In addition to storing the data in the numeric indices (field number) to the result array, it can also store the data using associative indices (field name). It stores both indicies by default.
For example :-
$arr = pg_fetch_array($result);
echo $arr["author"] . " <- Row 3 Author\n";
echo $arr[1] . " <- Row 3 E-mail\n";
pg_query() executes the query on the specified database connection.

For example :-
$result = pg_query($con, "SELECT * FROM $tablename where sr_no = 10");


pg_num_rows() will return the number of rows in a PostgreSQL result resource.
For example :-
<?php
$result = pg_query($conn, "SELECT 1");

$rows = pg_num_rows($result);

echo $rows . " row(s) returned.\n";
?>

Thursday, July 8, 2010

Basic points about Python

Python is a high-level, interpreted, interactive and object oriented-scripting language.
  • Python is Interpreted
  • Python is Interactive
  • Python is Object-Oriented
  • Python is Beginner's Language
Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands.


Python's Feature highlights include:
  • Easy-to-learn
  • Easy-to-read
  • Easy-to-maintain
  • A broad standard library
  • Interactive Mode
  • Portable
  • Extendable
  • Databases
  • GUI Programming
  • Scalable



    Reserved Words:


    The following list shows the reserved words in Python. These reserved words may not be used as constant or variable or any other identifier names.
    Keywords contain lowercase letters only.



    andexecnot
    assertfinallyor
    breakforpass
    classfromprint
    continueglobalraise
    defifreturn
    delimporttry
    elifinwhile
    elseiswith
    exceptlambdayield



    Standard Data Types:



    Python has five standard data types:

    • Numbers
    • String
    • List
    • Tuple
    • Dictionary



    The search Function


    This function search for first occurrence of RE pattern within string with optional flags.
    Here is the syntax for this function:

    re.string(pattern, string, flags=0)
    
    Here is the description of the parameters:



    ParameterDescription
    patternThis is the regular expression to be matched.
    stringThis is the string which would be searched to match the pattern
    flagsYou can specifiy different flags using exclusive OR (|). These are modifiers which are listed in the table below.
    The re.search function returns a match object on success, None on failure. We would use group(num) or groups() function of match object to get matched expression.



    Match Object MethodsDescription
    group(num=0)This methods returns entire match (or specific subgroup num)
    groups()This method return all matching subgroups in a tuple (empty if there weren't any)

    Matching vs Searching:

    Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default).



    Search and Replace:


    Some of the most important re methods that use regular expressions is sub.


    Syntax:

    sub(pattern, repl, string, max=0)
    
    This method replace all occurrences of the RE pattern in string with repl, substituting all occurrences unless max provided. This method would return modified string.

    Built-In Class Attributes:

    Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute:



    • __dict__ : Dictionary containing the class's namespace.
    • __doc__ : Class documentation string, or None if undefined.
    • __name__: Class name.
    • __module__: Module name in which the class is defined. This attribute is "__main__" in interactive mode.
    • __bases__ : A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.

Tuesday, July 6, 2010

Quick Python Tutorial

Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, case sensitive , together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms

The Python interpreter is easily extended with new functions and data types implemented in C or C++ (or other languages callable from C). Python is also suitable as an extension language for customizable applications.

Getting Help


Help in Python is always available right in the interpreter. If you want to know how an object works, all you have to do is call help(<object>)! Also useful are dir(), which shows you all the object’s methods, and <object>.doc, which shows you its documentation string:

>>> help(5)
Help on
int object: (etc etc)
>>> dir(5)
['__abs__', '__add__', ...]


Syntax 


Python has no mandatory statement termination characters and blocks are specified by indentation. Indent to begin a block, dedent to end one. Statements that expect an indentation level end in a colon (:). Comments start with the pound (#) sign and are single-line, multi-line strings are used for multi-line comments. Values are assigned (in fact, objects are bound to names) with the equals sign (”=”), and equality testing is done using two equals signs (”==“). You can increment/decrement values using the += and -= operators respectively by the right-hand amount. This works on many datatypes, strings included. You can also use multiple variables on one line. For example:
>>> myvar = 3
>>> myvar += 2
>>> myvar 5
>>> myvar -= 1
>>> myvar 4
"""This is a multiline comment.
The following lines concatenate the two strings."
""
>>> mystring = "Hello"
>>> mystring += " world."
>>> print mystring
Hello world.



DataTypes


The data structures available in python are lists, tuples and dictionaries. Sets are available in the sets library (but are built-in in Python 2.5 and later). Lists are like one-dimensional arrays (but you can also have lists of other lists), dictionaries are associative arrays (a.k.a. hash tables) and tuples are immutable one-dimensional arrays (Python “arrays” can be of any type, so you can mix e.g. integers, strings, etc in lists/dictionaries/tuples). The index of the first item in all array types is 0. Negative numbers count from the end towards the beginning, -1 is the last item. Variables can point to functions. The usage is as follows:


>>> sample = [1, ["another", "list"], ("a", "tuple")]
>>> mylist = ["List item 1", 2, 3.14]
>>> mylist[0] = "List item 1 again"
>>> mylist[-1] = 3.14
>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}
>>> mydict["pi"] = 3.15
>>> mytuple = (1, 2, 3)
>>> myfunction = len
>>> print myfunction(mylist)
3
You can access array ranges using a colon (:). Leaving the start index empty assumes the first item, leaving the end index assumes the last item. Negative indexes count from the last item backwards (thus -1 is the last item) like so:


>>> mylist = ["List item 1", 2, 3.14]
>>> print mylist[:]
['List item 1', 2, 3.1400000000000001]
>>> print mylist[0:2]
['List item 1', 2]
>>> print mylist[-3:-1]
['List item 1', 2]
>>> print mylist[1:]
[2, 3.14]

Strings

Its strings can use either single or double quotation marks, and you can have quotation marks of one kind inside a string that uses the other kind (i.e. “He said ‘hello’.” is valid). Multiline strings are enclosed in triple double (or single) quotes (”“”). Python supports Unicode out of the box, using the syntax u“This is a unicode string”. To fill a string with values, you use the % (modulo) operator and a tuple. Each %s gets replaced with an item from the tuple, left to right, and you can also use dictionary substitutions, like so:


>>>print "Name: %s\nNumber: %s\nString: %s" % (myclass.name, 3, 3 * "-")
Name: Poromenos
Number: 3
String: ---

strString = """This is
a multiline
string."
""


Flow control statements

Flow control statements are if, for, and while. There is no select; instead, use if. Use for to enumerate through members of a list. To obtain a list of numbers, use range(<number>). These statements’ syntax is thus:



rangelist = range(10)
>>> print rangelist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in rangelist:
    # Check if number is one of
    # the numbers in the tuple.
    if number in (3, 4, 7, 9):
        # "Break" terminates a for without
        # executing the "else" clause.
        break
    else:
        # "Continue" starts the next iteration
        # of the loop. It's rather useless here,
        # as it's the last statement of the loop.
        continue
else:
    # The "else" clause is optional and is
    # executed only if the loop didn't "break".
    pass # Do nothing

if rangelist[1] == 2:
    print "The second item (lists are 0-based) is 2"
elif rangelist[1] == 3:
    print "The second item (lists are 0-based) is 3"
else:
    print "Dunno"

while rangelist[1] == 1:
    pass


Functions

Functions are declared with the “def” keyword. Optional arguments are set in the function declaration after the mandatory arguments by being assigned a default value. For named arguments, the name of the argument is assigned a value. Functions can return a tuple (and using tuple unpacking you can effectively return multiple values). Lambda functions are ad hoc functions that are comprised of a single statement. Parameters are passed by reference, but immutable types (tuples, ints, strings, etc) cannot be changed. This is because only the memory location of the item is passed, and binding another object to a variable discards the old one, so immutable types are replaced. For example:

# Same as def f(x): return x + 1
functionvar = lambda x: x + 1
>>> print functionvar(1)
2

# an_int and a_string are optional, they have default values
# if one is not passed (2 and "A default string", respectively).
def passing_example(a_list, an_int=2, a_string="A default string"):
    a_list.append("A new item")
    an_int = 4
    return a_list, an_int, a_string

>>> my_list = [1, 2, 3]
>>> my_int = 10
>>> print passing_example(my_list, my_int)
([1, 2, 3, 'A new item'], 4, "A default string")
>>> my_list
[1, 2, 3, 'A new item']
>>> my_int
10

Classes

Python supports a limited form of multiple inheritance in classes. Private variables and methods can be declared (by convention, this is not enforced by the language) by adding at least two leading underscores and at most one trailing one (e.g. “__spam”). We can also bind arbitrary names to class instances. An example follows:

class MyClass:
    common = 10
    def __init__(self):
        self.myvariable = 3
    def myfunction(self, arg1, arg2):
        return self.myvariable

    # This is the class instantiation
>>> classinstance = MyClass()
>>> classinstance.myfunction(1, 2)
3
# This variable is shared by all classes.
>>> classinstance2 = MyClass()
>>> classinstance.common
10
>>> classinstance2.common
10
# Note how we use the class name
# instead of the instance.
>>> MyClass.common = 30
>>> classinstance.common
30
>>> classinstance2.common
30
# This will not update the variable on the class,
# instead it will bind a new object to the old
# variable name.
>>> classinstance.common = 10
>>> classinstance.common
10
>>> classinstance2.common
30
>>> MyClass.common = 50
# This has not changed, because "common" is
# now an instance variable.
>>> classinstance.common
10
>>> classinstance2.common
50

# This class inherits from MyClass. Multiple
# inheritance is declared as:
# class OtherClass(MyClass1, MyClass2, MyClassN)
class OtherClass(MyClass):
    # The "self" argument is passed automatically
    # and refers to the class instance, so you can set
    # instance variables as above, but from inside the class.
    def __init__(self, arg1):
        self.myvariable = 3
        print arg1

>>> classinstance = OtherClass("hello")
hello
>>> classinstance.myfunction(1, 2)
3
# This class doesn't have a .test member, but
# we can add one to the instance anyway. Note
# that this will only be a member of classinstance.
>>> classinstance.test = 10
>>> classinstance.test
10

Exceptions

Exceptions in Python are handled with try-except [exceptionname] blocks:

def some_function():
    try:
        # Division by zero raises an exception
        10 / 0
    except ZeroDivisionError:
        print "Oops, invalid."
    else:
        # Exception didn't occur, we're good.
        pass
    finally:
        # This is executed after the code block is run
        # and all exceptions have been handled, even
        # if a new exception is raised while handling.
        print "We're done with that."

>>> some_function()
Oops, invalid.
We're done with that.

Importing

External libraries are used with the import [libname] keyword. You can also use from [libname] import [funcname] for individual functions. Here is an example:

import random
from time import clock
randomint = random.randint(1, 100)
>>> print randomint
64

File I/O

Python has a wide array of libraries built in. As an example, here is how serializing (converting data structures to strings using the pickle library) with file I/O is used:

import pickle
mylist = ["This", "is", 4, 13327]
# Open the file C:\binary.dat for writing. The letter r before the
# filename string is used to prevent backslash escaping.
myfile = file(r"C:\binary.dat", "w")
pickle.dump(mylist, myfile)
myfile.close()

myfile = file(r"C:\text.txt", "w")
myfile.write("This is a sample string")
myfile.close()

myfile = file(r"C:\text.txt")
>>> print myfile.read()
'This is a sample string'
myfile.close()

# Open the file for reading.
myfile = file(r"C:\binary.dat")
loadedlist = pickle.load(myfile)
myfile.close()
>>> print loadedlist
['This', 'is', 4, 13327]

Miscellaneous

  • Conditions can be chained. 1 < a < 3 checks that a is both less than 3 and more than 1.
  • You can use del to delete variables or items in arrays.
  • List comprehensions provide a powerful way to create and manipulate lists. They consist of an expression followed by a for clause followed by zero or more if or for clauses, like so:

>>> lst1 = [1, 2, 3]
>>> lst2 = [3, 4, 5]
>>> print [x * y for x in lst1 for y in lst2]
[3, 4, 5, 6, 8, 10, 9, 12, 15]
>>> print [x for x in lst1 if 4 > x > 1]
[2, 3]
# Check if an item has a specific property.
# "any" returns true if any item in the list is true.
>>> any([i % 3 for i in [3, 3, 4, 4, 3]])
True
# This is because 4 % 3 = 1, and 1 is true, so any()
# returns True.

# Check how many items have this property.
>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 4)
2
>>> del lst1[0]
>>> print lst1
[2, 3]
>>> del lst1
  • Global variables are declared outside of functions and can be read without any special declarations, but if you want to write to them you must declare them at the beginning of the function with the “global” keyword, otherwise Python will bind that object to a new local variable (be careful of that, it’s a small catch that can get you if you don’t know it). For example:

number = 5

def myfunc():
    # This will print 5.
    print number

def anotherfunc():
    # This raises an exception because the variable has not
    # been bound before printing. Python knows that it an
    # object will be bound to it later and creates a new, local
    # object instead of accessing the global one.
    print number
    number = 3

def yetanotherfunc():
    global number
    # This will correctly change the global.
    number = 3