Home  Contents

Modules

In this part of the Python programming tutorial, we will talk about Python modules.

A module is a file in which we have Python code. The modules in Python have the .py extension.

There are several ways to manage Python code:

Python modules are used to organize Python code. For example, database related code is placed inside a database module, security code in a security module etc. Smaller Python scripts can have one module. But larger programs are split into several modules.

#!/usr/bin/python

# empty.py

"""
An empty module
"""

This is empty.py module.

#!/usr/bin/python

# modulename.py

import empty
import sys


print __name__
print empty.__name__
print sys.__name__

In this example, we print the names of modules.

$ ./modulename.py 
__main__
empty
sys

The name of the module, which is being executed is always __main__. Other modules are named after the file name. Modules can be imported into other modules using the import keyword.

The import keyword

The import keyword can be used in several ways.

from module import *

This construct will import all Python definitions into the namespace of another module. There is one exception. Object beginning with underscore character _ are not imported. They are expected to be used only internally by the module being imported. This way of importing modules is not recommended.

#!/usr/bin/python

# everything.py

from math import *

print cos(3)
print pi

This import construct has imported all definitions from the built-in math module. We can call the math funtcions directly, without referencing the math module.

$ ./everything.py 
-0.9899924966
3.14159265359

The use of this import construct may result in namespace pollution. We may have several objects of the same name and their definitions can be overriden.

#!/usr/bin/python

# pollution.py

from math import  *

pi = 3.14

print cos(3)
print pi

The example will print 3.14 to the console. Which may not be, what we wanted. The namespace pollution may become critical in larger projects.

The following example will show definitions, that are not being imported using this import construct.

#!/usr/bin/python

# names.py

"""
names is a test module
"""

_version = 1.0

names = ["Paul", "Frank", "Jessica", "Thomas", "Katherine"]

def show_names():
   for i in names:
      print i

def _show_version():
   print _version

This is the names.py module.

#!/usr/bin/python

# private.py

from names import *

print locals()

show_names()

The _version variable and the _show_version() function are not imported into the private.py module. We don't see them in the namespace. The locals() function give us all the definitions available in the private module.

$ ./private.py 
{'__builtins__': <module '__builtin__' (built-in)>, '__file__': './private.py', 
'show_names': <function show_names at 0xb7dd233c>, 
'names': ['Paul', 'Frank', 'Jessica', 'Thomas', 'Katherine'],
 '__name__': '__main__', '__doc__': None}
Paul
Frank
Jessica
Thomas
Katherine

from module import fun, var

This import construct imports only specific objects from a module. This way we import only definitions that we need.

#!/usr/bin/python

# immath.py

from math import sin, pi


print sin(3)
print pi

We import two objects from the math module. There is no way, how we could reference other definitions like e.g. a cos function.

#!/usr/bin/python

# imnames.py

from names import _version, _show_version

print _version
_show_version()

We could also import definitions beginning with an underscore. But this is a bad practice.

$ ./imnames.py 
1.0
1.0

import module

The last construct is most widely used. It prevents the namespace pollution and enables to access all definitios from a module.

#!/usr/bin/python

# widely.py

import math

pi = 3.14

print math.cos(3)
print math.pi
print math.sin(3)
print pi

In this case, we reference the definitions via the module name. As we can see, we are able to use both pi variables. Our definition and the one from the math module.

$ ./widely.py 
-0.9899924966
3.14159265359
0.14112000806
3.14
#!/usr/bin/python

# importas.py

import math as m

print m.pi
print m.cos(3)

We can change the name through which we can reference the module. To do this, we use the as keyword.

$ ./importas.py 
3.14159265359
-0.9899924966

Executing modules

Modules can be imported into other modules or they can be also executed. Module authors often create a testing suite to test the module. Only if the module is executed as a script, the __name__ attribute equals to __main__.

We will demonstrate this on a fibonacci module. Fibonacci numbers is a sequence of numbers, where each is the sum of its two immediate predecessors.

#!/usr/bin/python

# fibonacci.py

"""
A module containing the fibonacci
function. 
"""

def fib(n):
    a, b = 0, 1
    while b < n:
        print b,
        (a, b) = (b, a + b)


# testing

if __name__ == '__main__':
   fib(500)

The module can be normally imported as usual. The module can be also executed.

$ ./fibonacci.py 
1 1 2 3 5 8 13 21 34 55 89 144 233 377

If we do import the fibonacci module, the test is not executed automatically.

>>> import fibonacci as fib
>>> fib.fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

This chapter was about modules in Python.