Python modules

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata
Created: bogdan.galiceanu (23 Nov 2007)
Last edited: hamishwillee (06 Feb 2012)

Python modules (also called extensions) are collections of functions that can be imported. They are useful for giving Python special capabilities, which aren't normally loaded at startup, and storing your own functions for quick importing and using later.

import module
from module import *
#these import the entire module
from module import function
#this only imports the named function
#where module is the name of the module and function is the name of the function that needs to be imported

In order to see what functions are available in a module, we use the "dir" function:

import module
print dir(module)
#this displays the functions, in alphabetical order:
['function1', 'function2', ...]

For example, the functions contained by the module "math" are:

import math
print dir(math)
['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']

Let's say we have 2 modules, each containing a function of the same name, "execute". Each of the 2 executes does something completely different. In order to use them, we have the following options:

import module1
import module2
#this means you specify from which module to use the function
#importing the modules as something else (which means giving them different names)
import module1 as m1
import module2
#this may not seem useful in this example, but it is good to know that modules can be imported with different names
#importing the functions with different names
from module1 import execute as e1
from module2 import execute as e2

On the PC version of Python, any .py file can be a module. Suppose we have the file "mymodule.py", which only contains the instruction 'print "a module"', that we want to use as a module. Here's how to do it:

#first we need to append the default modules locations with ours
#this means we tell Python where to look for our module
>>>import sys
#where filepath is the location of our "mymodule" program
#next we just import it and see the results
>>>import mymodule
a module

The same method is used for defining functions and storing them in a module, which is the most common use of a module.

PyS60 modules are usually written in C++. For unofficial, user-made modules, follow this link:

PySymbian C++ Extensions

This page was last modified on 6 February 2012, at 06:45.
45 page views in the last 30 days.