Modules and Packages
Learn about the modules and packages in Python.
We'll cover the following...
Why do we need a module?
Now we know how to create classes and instantiate objects. We don’t need to write too many classes (or non-object-oriented code, for that matter) before we start to lose track of them. For small programs, we generally put all our classes into one file and add a little script at the end of the file to start them interacting. However, as our projects grow, it can become difficult to find the one class that needs to be edited among the many classes we’ve defined. This is where modules come in. Modules are Python files, nothing more. The single file in our small program is a module. Two Python files are two modules. If we have two files in the same folder, we can load a class from one module for use in the other module.
Module name
The Python module name is the file’s stem; the name without the .py
suffix. A file named model.py
is a module named model
. Module files are found by searching a path that includes the local directory and the installed packages.
Import module
The import
statement is used for importing modules or specific classes or functions from modules. We’ve already seen an example of this in our Point
class in the previous section. We used the import
statement to get Python’s built-in math module and use its hypot()
function in the distance calculation. Let’s start with a fresh example.
Real-world example
If we are building an e-commerce system, we will likely ...