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 — askyb.py
# This function will return my name
# 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:
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.
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.
'World Wide Wed'
'World Wide Wed'
>>> GetTotal(2, 8)