Python – install pip on 64bit Windows

To install pip on Windows, you need to first install its predecessor – easy install. However, if you’re using a 64-bit distribution of  Python then the .exe installers here will give you this error when you run it:


This is due to a distutils installer compatibility issue, but all’s not lost, you just need to download the and run it, it will then download the appropriate .egg file and install it for you.

You then need to add the Scripts folder in your Python distribution, e.g. C:\Python27\Scripts to the Windows path, and open up a DOS prompt and run easy_install pip and voila!

Learning Python – Coding Style

  • Use 4-space indentation, no tabs


  • Wrap lines so that they don’t exceed 79 characters


  • 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


  • 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

    Naming conventions:

    Variables / functions – use_lower_case_separated_by_underscore

    Class names – UseCamelCase

    Error classes end in Error, i.e. MyError

Learning Python – Part 5


A while back I decided to try and learn Python for the hell of it as it seems like an interesting language and has some of the most concise and user-friendly syntax. Having spent some time going through a number of different learning sources and materials (like the official site which has a very helpful tutorial section) I have put together a set of notes I made as I was learning and hopefully they can be useful to you as a quick list of how-to code snippets.

All the code snapshots I’m showing here are taken from the IDLE Python shell.

Input and Output

The repr() function generates representations that can be read by the interpreter, str() function generates a human-readable of the value:



If an object doesn’t have a particular representation for human consumption, str() will return the same value as repr(), e.g. lists and dictionaries:



You can use the string.rjust(), string.ljust() or function to left-justify, right-justify or center a string of given width by padding it with spaces:



You can use the string.zfill() function to pad a numeric string on the left with zeros:



You can use string.format() method to format the string output of your code:



You can also use named arguments:



An optional ‘:‘ and format specifier can follow the field name to allow greater control over how the value is formatted:



Passing an integer after the ‘:‘ will cause that field to be a minimum number of characters wide:



For a very long string, you could even reference variables to be formatted by name using a dictionary:


Or you could unpack the dictionary first:



You can use the open() function to get a file object, to open a file for writing:


The first parameter being the file name, the second the mode which can be one of the following:



To open a file and read its contents:



To read one line at a time



To read the lines in the file as an array of strings:



You can also read x number of bytes at a time:



But remember, you always read starting from the position where your last read finished:



To write to a file:



You can only write string contents to a file, which means you’d need to convert other objects to string first:



To flush the file buffer and actually write them to the file, use the close() function, after which you’ll need to open the file again:



You can use the tell() function to find out your current position in the file:



You can use the seek() function to change the file object’s current position, seek(offset, from_what):


from_what can be one of three values:

  • 0 – beginning of file (default)
  • 1 – current position
  • 2 – end of the file



It’s good practice to use the with keyword when dealing with file objects, which ensures that the file is closed after its suite finishes. (this works like the using keyword in C#).



To deal with complex types (or indeed any non-string types like int) you can use the pickle module to convert it to and from string.

The process of converting a complex type to string is called pickling.

The process of constructing a complex type from string is called unpickling.




try-except block:



You can handle more than one exception if you name them in a tuple:



You can handle a list of exceptions in a certain priority list and if you don’t specify a particular exception type it’ll serve as a wildcard:



You can also specify a else clause which follows all except clauses, it’s useful for code that must be executed if the try clause does not raise an exception:


The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try-except statement.


There’s also the optional finally clause which is intended to define clean-up actions that must be executed under all circumstances:



You can get more information about the instance of the exceptions:




To throw an exception:



To re-throw an exception:



To define a custom exception:


The __str__() function ensures that you can print the exception instance directly:



When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions:



Some objects define standard clean-up actions, for instance, the with statement always closes the file after the statement is executed:


(the same as the using statement in C#)

Learning Python – Part 4


A while back I decided to try and learn Python for the hell of it as it seems like an interesting language and has some of the most concise and user-friendly syntax. Having spent some time going through a number of different learning sources and materials (like the official site which has a very helpful tutorial section) I have put together a set of notes I made as I was learning and hopefully they can be useful to you as a quick list of how-to code snippets.

All the code snapshots I’m showing here are taken from the IDLE Python shell.


Some notable differences from the class mechanism in C#:

  • The class inheritance mechanism allows multiple base classes
  • Classes are created at runtime and can be modified further after creation
  • All class members are public by default
  • All class members are virtual
  • Classes themselves are objects

Like many other languages, most built-in operators with special syntax (arithmetic operators, subscripting etc.) can be redefined for class instances.


Simple class definition:



To instantiate a new class:



To define a constructor which takes in some parameters:


to instantiate this class:



When a class defines an __init__() method, class instantiation automatically invokes this method for the newly-created class instance.


To access its attributes:



To access its docstring:



There are only two kinds of valid attribute names, data attributes and methods.


Data attributes don’t need to be declared, they simply spring into existence when they are first assigned to. For instance, for the Person class defined above, we can add a new data attribute to an existing instance:


note that the new data attribute belongs to the instance referenced by x, and doesn’t exist on any other instance of the Person class (think Javascript)


You can delete the data attribute after you’re done with it:



Data attributes can be override by users of an object, so to avoid accidental name conflicts it’s best practice to use some kind of convention that minimize the chance of conflicts. E.g. capitalizing method names, prefixing data attribute names with a small unique string, or using verbs for methods and nouns for data attributes.


It’s important to note that nothing in Python makes it possible to enforce data hiding, it’s all based on convention.


NOTES: Difference between a function and a method is that a method is a function bound to a class.


To define a method on the class:



To call the method:


You may have noticed that in the method definition say_greeting takes a single parameter self but it was called with none. This is a special rule which applies to methods where the object is passed as the first argument. The convention is to call the first argument of a method self.


It’s not necessary that the function definition is textually enclosed in the class definition:


and you can still use it like before:



To call other methods inside the class:



To find the class of an instance:



To created a derived class:


because we haven’t defined any new attributes, everything will be inherited from Person including the __init__ method:



If a requested attribute is not found in the class, the search proceeds to look in the base class and if still not found it proceeds to look in the base class of that class, and so on.

You can also extend a base method instead of replacing it, to call a base class method:



Use isinstance() function to check if an object is an instance of a class or some class derived from it:



Use issubclass() function to check if a class derives from another:



Every class keeps these built-in attributes:

  • __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.



Python’s garbage collector runs during program execution and is triggered when an object’s reference count reaches zero.

You can implement a destructor, __del__() method, that is invoked when the instance is about to be destroyed.


Here’s a list of some of the methods you can override in your own class:



Python supports multiple inheritance:



Whilst you can’t hide an object’s attributes you can still make them not directly visible to outsiders by adding a double underscore prefix:


What’s happened is that Python changed the name of these attributes to include the class name:


So you can still access them like this:


This is called name mangling it is mostly designed to avoid accidental name conflicts as opposed to provide data hiding.


Most container objects can be looped over using a for statement, underneath, the for statement calls iter() on the container object and gets back an object that defines the method next(). When there are no more elements, next() raises a StopIteration exception which tells the for loop to terminate.


Here’s how you might create a custom iterator which loops through a container object in reverse:





A module allows you to logically organize your Python code, a module is a file containing Python definitions and statements.

The file name is the module name with the .py extension.

Within a module, the module name is available as the value of the global variable __name__.

You can import an entire module in your code, or just specific subset of the functions defined in the module. For example, to import the definitions in a file called ‘’ in the current directory:



A module can contain executable statements as well as functions, these statements are intended to initialize the module and are executed only the first time the module is imported somewhere.


Each module has its own private symbol table which is used as the global symbol table by all the functions defined in the module. This way, you won’t have to worry about accidental clashes with global variable names. However, if required, you could still access a modules global variables with modulename.itemname.


You can import a subset of the items from a module using a variant of the import statement. To import specific functions or variables:



You can import all names from a module except those beginning with an underscore:



You can use the python executable to run a python script:


When you do this, the __name__ global variable of the script is changed to __main__, and by adding the following lines to your script you can make the file usable as a script as well as an importable module:




When you ask to import a module called fib, Python first looks for a file named in the current directory, if not found it then looks in the list of directories specified by the environment variable PYTHONPATH.

You mustn’t name your script the same as a standard module, or Python will attempt to load the script as a module when that module is imported..


To improve the start-up time of short programs that use a lot of standard modules, python generates a compiled version of the module. For instance, for the module fib, the fib.pyc contains a byte-compiled version of the file. The modification time of the version of used to create fib.pyc is recorded in fib.pyc file and is used to determine whether fib.pyc is up to date and therefore if it could be used.

However, it’s worth noting that a program doesn’t run faster when it’s read from a .pyc file instead of .py file, it’s only loaded faster.

When a script is run from the command line the byte-code for the script is never written to a .pyc file. You can improve the load time for these scripts by moving most of its code to a module and having a small bootstrap script that imports that module.

It’s possible to have a .pyc file without the corresponding .py file, this can be used to distribute a library of Python code in a form that is moderately hard to reverse engineer.


You can use the compileall module to create .pyc files for ALL .py files in a directory:

clip_image007[4] is one of the standard modules, and use sys.path you can see all the paths which Python will look when it’s trying to find a module to import:


Of course, you can add to that path:


But remember, this change is only valid in the current session, when you restart the interpreter this new path will be lost.


To find out what names are defined in a module, use the built-in dir() function:



Without argument, dir() lists all the names you have defined currently:


Another handy thing you can do with the dir() function is to use to list all the built-in functions:



You can put a collection of related modules in a package. Here’s a possible structure for a sound package in terms of file hierarchies:


The files are required to make Python treat the directories as containing packages. It can be an empty file, but it can also execute initialization code for the package.


To import an individual module of the package:


But it must be referenced with its full name:



Alternatively you could also:


The benefit of this approach is so that you don’t need the full name to reference it:



Or, if all you want is the echofilter function, you could also:


And to reference it:



When the users write from sound.effects import * the import statement uses the following convention:

  • If a package’s code defines a list named __all__, it is taken to be the list of modules names that should be imported when from package import * is encountered:


  • If __all__ is not defined, from sound.effects import * only ensures that the package sound.effects is imported and run any initialization code in


The recommended approach is to import specific modules using from Package import module.


You can also relative paths from the current module, so from the surround module you might:


Where . refers to the current package, .. refers to the parent package, ..filters refers to the filters package at the same level as the parent package

Because the name of the main module is always "__main__", therefore modules intended for use as the main module of a Python application should always use absolute imports.

Learning Python – Part 3


A while back I decided to try and learn Python for the hell of it as it seems like an interesting language and has some of the most concise and user-friendly syntax. Having spent some time going through a number of different learning sources and materials (like the official site which has a very helpful tutorial section) I have put together a set of notes I made as I was learning and hopefully they can be useful to you as a quick list of how-to code snippets.

All the code snapshots I’m showing here are taken from the IDLE Python shell.


A set is an unordered collection with no duplicate elements. To create a set:


notice how the duplicate was removed?


You can also use a string as a sequence of char objects and turn it into a set:



Now, let’s use this two simple sets to illustrate some basic set operations:


Set difference:


Set union:


Set intersect:


Exclusive (in one or the other but not both):




Dictionaries are key value pairs indexed by keys, which can be any immutable type. To create an empty dictionary:



You access the elements in a dictionary using square brackets [], you can find out all the keys and values in a dictionary using the keys and values methods:



You can also use the del statement to delete a key value pair:



You can create a dictionary using the dict() method and pass in a sequence of tuples:


if the keys are all strings, you can even do this:



To loop through dictionaries, the key and corresponding value can be retrieved at the same time using the iteritems() method:




Use a while loops to generate the Finobacci sequence:



For loops:



Mutable sequences like lists should not be modified at the same time as looping through it, and instead should be done on a copy:


what would happen if we don’t use a copy here? This code will get stuck in an infinite loop:



The else and break statement:

Loops in Python can have an else clause which is executed when the loop terminates through exhaustion of the list (for for loops) or when the loop condition becomes false (for while loops), but it won’t execute if the loop is terminated with the break statement:



The continue statement:



The pass statement:

It does nothing, often used to create a minimal class..




Use the def keyword to define a function:


Note that the first string is a docstring that can be used by some tools to generate documentations.


Arguments are passed using call by reference, as the argument is always an object reference not the value of the object.

Every function has a return value, if nothing is returned then a special None value is returned. Writing of the None value is usually suppressed by the interpreter, but you can see it using print:



Use the return keyword to return values from a function:



Default argument values:



The default values are evaluated once and once only, at the point of function definition:


however, it works differently with mutable objects such as lists, dictionaries etc.


notice how the second function call didn’t use the default empty list? That’s because the object referenced by the variable l is mutable and its state was mutated by the first add_item call.


You can also call the function using keyword arguments if they appear AFTER the regular parameters have been passed in:


note that keyword arguments cannot be provided twice.


You can define an arbitrary argument list which takes in a tuple:



Similarly, you can take in a dictionary:



Interestingly, the reserve of the above is true too! You can take a tuple and unpacking it with the * operator:



Or take a dictionary and unpacking it with the ** operator: