Modules (aka libraries) are how Python developers share functionality they have created with the rest of the Python community.
Python is bundled with a large range of modules in what is called the Python Standard Library.
These encompass a very wide range of functionalities including
os
: “Miscellaneous operating system interfaces”os.path
: “Common pathname manipulations”sys
: “System-specific parameters and functions”math
: “Mathematical functions”random
: “Generate pseudo-random numbers”csv
: “CSV File Reading and Writing”which are modules that I use regularly. The full list is much, much more extensive and includes things like
tkinter
: “Python interface to Tcl/Tk” (For creating simple Graphical User Interfaces)wave
: “Read and write WAV files” (Audio)ftplib
: “FTP protocol client”http.server
: “HTTP servers” (i.e. Web server)email
: “An email and MIME handling package”multiprocessing
: “Process-based parallelism”zipfile
: “Work with ZIP archives”to name an assortement of Standard Library modules I’ve used less frequently.
The total list contains hundreds of modules, and covers a wide spectrum of things you can do with a computer!
In addition to the Standard Library, there are many thousands more
(69544(from January this year) 93151 (now!)
at last count) modules listed in the Python Package Index, that range
from modules created by lone developers to projects involving hundreds to
thousands of developers over many years, such as Scipy.
You can browse the list at of modules at
the Python Package Index
or use the search interface to find modules by keywords.
To use a Python module we must first import
it,
import MODULENAME
Once imported, we access a modules functions using the dot notation,
<MODULENAME>.<FUNCTIONNAME>(...)
.
For example, above we used the random
module to generate random numbers,
so after the line
import random
we were able to call a module function using, e.g.
random.random()
Python also allows us to provide an alias for a module, which is a different way of refering to it. For example if I wrote
import random as rnd
I would then be able to later use the random.random
function by writing
rnd.random()
This can be handy, especially when using modules with long names, or a submodule of a submodule of a submodule!
Lastly, submodules or functions can also be imported individually if desired,
by using the from
syntax:
from MODULE import FUNCTION
or
from MODULE.SUBMODULE import FUNCTION
to import a function from a module or submodule, which will then be accessible as FUNCTION (i.e. without needing to specify the module name!).
Similarly
from MODULE import SUBMODULE
imports a submodule without needing to prefix it with the module name.
Creating a module is extremely simple in Python. In fact we’ve created several modules already!
Any file ending in .py
is a simple module!
If for example we create a script file called mymod.py
and
in that script we define a function (which we’ll learn about
in the last section of this workshop)
called super_function
, then
we can create another file and import that module using
import mymod
This then gives us access to the function we defined, e.g.
mymod.super_function
if __name__ == "__main__":
to hide script codeWhen writing a script to be used as a module, it is useful to have a mechanism for running part of the script only if the script is being run as a script, and not being imported!
This is because when a script is imported, it is essentially run!
To “hide” code from being run when imported Python introduced the following pattern:
def function1():
...
def function2():
...
if __name__ == "__main__":
print("I'm being run as a script lets do script stuff!")
function1(10,20)
We’ll cover the function definitions for the functions function1
and
function2
in the next section. Of interest here is the last part of the snippet;
by using the special built-in variable __name__
and checking whether it is equal to
"__main__"
, we can check if the file is being run as a script or imported.
This is because the __name__
variable is only equal to "__main__"
when being run as
a script; if the file is being imported, then __name__
becomes the name of the module.
While it’s important to understand that it’s actually very easy to create a Python module, doing so isn’t necessary for the context of this course, and so we won’t be practicing this here.
Advanced Users: module folders
More complex modules are created by using a folder or folders that contain a file named in a special way (
__init__.py
). For example if we have a folder tree:joesModule / __init__.py submodule1.py submodule2.py
Then we can use
import joesModule.submodule1
to import the functionality contained in
submodule1.py
.