Previous | Next

A module is simply a text file that contains Python code. Your code will become highly reusable when your turn them into a module.

Create and save your code:

To turn your function into a module, save your code into a Python extension file. Let’s save the following code into a Python extension file —
def GetMyName():
  # This function will return my name
  return 'askyb'

def GetMyLocation():
  # This function will return my location
  return 'World Wide Wed'

def GetTotal(x, y):
  # This function will return sum of x & y
  return x + y

Tells the interpreter where to look for your module:

You will need to tell the Python interpreter where to look for your python code file. It can be done by include your module directory in the environment variable PYTHONPATH.

Add PYTHONPATH into UNIX and Mac OS X:

export PYTHONPATH=$PYTHONPATH:~/<directory name>

Add PYTHONPATH into Windows:

From the Start menu, select Start -> Settings -> Control Panel. In the Control Panel, double-click the System icon. In the dialog box that opens, select the Advanced tab and click the Environment Variables button. That brings up another dialog box with two tables: one with your user variables and one with system variables. You are interested in the system variables. If you see PYTHONPATH there already, select it, click Edit, and edit it. Otherwise, click New and use PYTHONPATH as the name; enter your directory as the value.

You will need to restart your machine in Windows.

Import your module:

Start the Python interpreter now. Use import keyword in order to import your module into the interpreter.
>>> import askyb
Notice that you import the module without specify the file extension (.py)

Calling your module functions:

All code in Python is associated with a namespace. When we put our code into its own module, Python automatically creates a namespace for our module. So, in this example, we create a module called askyb and it’s associated with a namespace called askyb too. The following show you how to call the functions in askyb module.
>>> import askyb
>>> askyb.GetMyName()
>>> askyb.GetMyLocation()
'World Wide Wed'
>>> askyb.GetTotal(2,8)
When you use a plain import statement, such as import askyb, the Python interpreter is instructed to allow you to access askyb’s functions using namespace qualification. However, it is possible to be more specific. Try with the following example:
>>> from askyb import GetMyName, GetMyLocation, GetTotal
>>> GetMyName()
>>> GetMyLocation()
'World Wide Wed'
>>> GetTotal(2, 8)
Such implementation will add the functions to the current namespace, effectively removing the requirement for you to use namespace qualification.

Previous | Next