Python: Installing packages with easy_install

A lot of Python packages are available online at the Python Package Index (PyPI) repository. The advantage of using PyPI is that packages available there can be installed directly from the command-line. These packages can also be upgraded or uninstalled directly from the command-line.

To be able to do install directly from PyPI, one last package needs to be downloaded and installed manually: setuptools. Follow the installation instructions for setuptools from an Administrator command-prompt and remember to add the Scripts directory to the PATH.

After setuptools is successfully installed, its easy_install script can be used to install any package from the command-line. For example, to install a package named foobar from PyPI:

$ sudo easy_install foobar

Note that setuptools is not available for Python 3.x. If you are using Python 3.x, look at distribute instead.

Related: For information on installing downloaded packages go here.

Tried with: setuptools 0.6c11 and Python 2.7.3 64-bit

ROT13 in Python 3

Obtaining the ROT13 encoding of a string used to be easy in Python 2.x:


s = "Hello"
os = s.encode( "rot13" )
print( os ) # "Uryyb"

view raw

Rot13Python2.py

hosted with ❤ by GitHub

This no longer works in Python 3.x. The solution that works in Python 3.x is to access low-level functions in the codecs module:


import codecs
s = "Hello"
enc = codecs.getencoder( "rot-13" )
os = enc( s )[0]
print( os ) # "Uryyb"

view raw

Rot13Python3.py

hosted with ❤ by GitHub

Tried with: Python 3.2.3

Size of objects in Python

The getsizeof function from the sys module can be used to obtain the size of objects in Python. Comparing the size of elementary objects in Python with that in other languages can be quite interesting.


# Tried with Python 3.2.2 64-bit
import sys
a = None
sys.getsizeof( a ) # 16
a = 0
sys.getsizeof( a ) # 24
a = 12345678
sys.getsizeof( a ) # 28
a = ""
sys.getsizeof( a ) # 58
a = "hello"
sys.getsizeof( a ) # 68 (2 bytes per letter)
a = []
sys.getsizeof( a ) # 64
a = tuple()
sys.getsizeof( a ) # 48
a = set()
sys.getsizeof( a ) # 224
a = {}
sys.getsizeof( a ) # 272

view raw

ObjectSize.py

hosted with ❤ by GitHub

None returned by function in Python

This will seem odd to programmers from other languages. In Python, a function that has no return statement or an exit path in the function that has no return statement actually returns None. So, a variable can be used assign the return value of such functions. This also means that one does not need to worry about every exit path in the function. In languages like C, such behaviour would be a compilation error.


def foo( x ):
print( x )
y = foo( 10 )
if y is None:
print( "foo returned None" ) # Printed
else:
print( "No, it did not!" )

view raw

ReturnNone.py

hosted with ❤ by GitHub

Tried with: Python 3.2

Character translation in Python

Python has a couple of functions that make it easy to replace characters in a string with other characters. bytes.maketrans() is used to create the translation table. string.translate() uses this table to replace the matching characters in the string with their replacements in the table.


# Replace 'a' with '1', 'b' with '2' and 'c' with '3'
table = bytes.maketrans( b"abc", b"123" )
s = "abracadabra"
s2 = s.translate( table )
print( s2 ) # 12r131d12r1

Tried with: Python 3.2

eval in Python

eval in Python works like in many functional programming languages. It evaluates the input string as if it were a Python expression. Python’s eval can only handle expressions, so is pretty limited.


x = 1
y = eval( "x + 1" ) # 2
f = eval( "lambda x: x * x" )
g = f( 10 ) # 100

view raw

Eval.py

hosted with ❤ by GitHub

Tried with: Python 3.2

Adding function attributes in Python

A surprising feature in Python is that attributes can be added to functions at any point in the runtime. Both inside and outside the function the attribute is referred to as functionName.attribute. The attribute comes to life only when it is first set with a value. Trying to use an attribute that is not yet alive, results in AttributeError.


def foo():
return foo.x
print( foo() ) # AttributeError: 'function' object has no attribute 'x'
foo.x = 10
print( foo.x ) # 10
print( foo() ) # 10

Tried with: Python 3.2

Generator function in Python

A generator function is useful to produce values one by one when needed. It uses the yield statement to return the next value. When a generator function is called, a generator object is produced. By calling next() on this object, new values can be generated. When the function returns (not yields), then a StopIteration exception is generated.


# Infinite sequence generator
def sequenceGen():
i = 0
while True:
yield i
i += 1
g = sequenceGen()
print( next( g ) ) # 0
print( next( g ) ) # 1
print( next( g ) ) # 2

Tried with: Python 3.2

Function name in Python

The __name__ attribute of a function holds the function name. Even if the function is assigned to a new variable, its name remains the name with which it was originally defined. Lambda functions have the name <lambda>


def squareIt( x ):
return x * x
print( squareIt.__name__ ) # squareIt
foo = squareIt
print( foo.__name__ ) # squareIt
squareIt = lambda x: x * x
print( squareIt.__name__ ) # <lambda>
foo = squareIt
print( foo.__name__ ) # <lambda>

view raw

FunctionName.py

hosted with ❤ by GitHub

Tried with: Python 3.2

Generate random float in Python


import random
# Random float in [0.0, 1.0)
a = random.random()
# Random float in [0, 100]
b = random.uniform( 0, 100 )

view raw

RandomFloat.py

hosted with ❤ by GitHub