Module & Package#

Module#

A module is a python file that organizes a set of functions, classes, and variables for a specific task/goal in your program. In your project, a module is a way to organize your codes by functionality and make it more reusable. The module (i.e., python file with many functions and classes) can be imported in another python file, and the simple example is the import of existing modules from packages.

To use a module, you will use the import statement. Example:

import math

result = math.sqrt(16)
print(result)  # Output: 4.0
4.0

Package#

Packages are everywhere in python! A package offers a modular code organization, where the related modules are grouped in a logical way. A package is nothing more than a directory with a special file called init.py. Of course, this is an empty package but it’s a package because you have a marker (init.py) saying to your python this is a package.

In real application, your package (i.e., directory) contains one or more module files in a logical and organized way. The special file (init.py, empty file) serves as a marker in the directory so the python knows it’s a package. A simple way to organize your package is following:

my_package/
    __init__.py
    module1.py
    module2.py
    subpackage/
        __init__.py
        module3.py

In this example, my_package directory is a package that contains two main modules, module1.py and module2.py, as well as a subpackage called subpackage that contains its own init.py file and a module called module3.py.

from my_package import module1
from my_package.subpackage import module3

module1.function1()
module3.function2()