What is a Module?
A module is simply a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Modules allow you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use.
Imagine you have a file named my_math.py:
Python
# my_math.py
PI = 3.14159
def square(number):
    return number * number
You can now use the functions and variables from this module in another script.
The import Statement
To use the code from a module, you need to import it into your current script. There are a few ways to do this.
1. Basic Import
This imports the entire module. You then access its contents using module_name.member_name.
Python
# main.py import my_math area = my_math.PI * my_math.square(5) print(area) # Output: 78.53975
2. Import with an Alias
You can give the imported module a shorter name (an alias) using the as keyword. This is very common for modules with long names, like matplotlib.pyplot as plt.
Python
# main.py import my_math as mm area = mm.PI * mm.square(5) print(area)
3. Importing Specific Members
If you only need a few specific things from a module, you can import them directly using from. This adds them to your current script's namespace, so you don't need to prefix them with the module name.
Python
# main.py from my_math import PI, square area = PI * square(5) # No need for 'my_math.' prefix print(area)
Caution: Be careful with from module import *. It imports everything and can lead to name conflicts and make your code harder to read.
What is a Package?
A package is a way of structuring Python’s module namespace by using "dotted module names". In simple terms, a package is a directory that contains Python modules and a special __init__.py file (which can be empty).
This allows you to group related modules together under a single package name.
my_project/
├── main.py
└── my_app/
    ├── __init__.py
    ├── utils.py
    └── models.py
In this structure, my_app is a package. You could import the utils module like this in main.py: import my_app.utils or from my_app import utils.
The Python Standard Library & PyPI
Python comes with a huge Standard Library of modules that are available right after you install it. These include modules for working with math (math), random numbers (random), dates and times (datetime), and much more.
Beyond the standard library, there is a vast repository of third-party packages called the Python Package Index (PyPI). You can install these packages using a tool called pip (e.g., pip install requests).