Codeskill

Learn to code, step by step

Modules and Packages: Expanding Your Python Toolbox

Python modules and packages matters once your pages get past the basics. How to split code into reusable files, import what you need, and install third-party libraries from PyPI.

Modules

A module is a .py file containing Python definitions and statements. Modules let you organise code into logical chunks and reuse it across projects.

Creating and using a module

Say you create my_module.py:

# my_module.py
def greeting(name):
    print("Hello, " + name)

Import it in another file:

# another_file.py
import my_module

my_module.greeting("Python Programmer")  # Outputs: Hello, Python Programmer

Importing specific objects

Pull in just what you need:

from my_module import greeting

greeting("World")  # Outputs: Hello, World

Renaming a module

Use as for shorter or non-conflicting names:

import my_module as mm

mm.greeting("Pythonista")  # Outputs: Hello, Pythonista

Built-in modules

Python ships with a standard library. Import these the same way as your own modules:

import math

print(math.pi)  # Outputs: 3.141592653589793

Packages

A package is a directory of related modules. It needs an __init__.py file (can be empty) so Python treats the folder as a package.

Creating a package

Organise module1.py and module2.py like this:

mypackage/
    __init__.py
    module1.py
    module2.py

Import from the package:

import mypackage.module1
import mypackage.module2

Subpackages

Packages can contain nested packages:

mypackage/
    __init__.py
    module1.py
    module2.py
    subpackage1/
        __init__.py
        submodule1.py

Why bother?

Modules and packages keep code organised, reusable, and easier to maintain. Write a function once, import it wherever you need it.

Third-party packages

PyPI (Python Package Index) hosts thousands of libraries for almost any task. Install them with pip:

pip install requests

That installs requests, a popular library for making HTTP requests.

PreviousFile Handling in Python: Reading and Writing Files