Chapter 4: Python modules

Modules

face Josiah Wang

Let us take a quick detour before coming back to objects.

So far, you have used the import statement to import existing modules provided by the Python Standard Library.

Try the following!

>>> import random
>>> type(random)
<class 'module'>
>>> print(random)
<module 'random' from '/usr/lib/python3.8/random.py'>

Equipped with your latest knowledge about classes, you might observe that random is an instance of the module class.

More interestingly, you can also see that the random module is loaded from '/usr/lib/python3.8/random.py' (or wherever it points to on your computer).

In Python, a module is just a *.py file that contains Python statements, variables, and/or function and class definitions. It is basically a script that can be imported into another script.

So you can simply write some piece of code, save it as a script, and import and use this script from another script.

A module usually contains a collection of related functions/class definitions that can be reused. Think about the modules that you have used so far: math, random, string. They are usually modular and can be ‘dropped’ into another script to be used.

Modules are useful for breaking down large programs. Think of all those functions you wrote in your robot project so far!

Modules also allow you to reuse your code. For example, you can simply import a function or class you have written from a module instead of copying and pasting the code into a new file.