9) a. Modules

Python scripts are saved with the extension .py. Any .py file that contains Python code is called a “module”.

A module can be executed directly by running the following code on the command line:

python module.py

(Where “module.py” is your python file), or it can be imported into other modules as well.

Consider a python file that is created with the following code.

1
2
3
4
# This file is saved as "useful_functions.py"

def do_something_useful():
    return None

And now you can easily create another file where you call this method:

1
2
3
4
5
# This file is saved as "my_script.py"

import useful_functions

useful_functions.do_something_useful()

Modules are used to organize by separating it into multiple files.

Note: To import a module it is important that it must lie in either the system PATH or the PYTHONPATH. Just like PATH is a system variable, PYTHONPATH is also a system variable which may or may not be present on your system. Python will try to look into both of these paths to import your module.

If your module lies in the same folder then you can import it with the statement from <module_name> import *.