Modules
Modules are files containing Python code. They can define functions, classes, and variables. Python modules are imported using the import keyword.
| Python | |
|---|---|
Importing Specific Items
You can import specific items from a module using the from keyword.
| Python | |
|---|---|
Aliasing Modules
You can alias a module using the as keyword.
| Python | |
|---|---|
Standard Library
Python comes with a standard library that provides a wide range of modules for performing various tasks. You can find the list of standard library modules here.
Third-Party Libraries
In addition to the standard library, Python has a vast ecosystem of third-party libraries that can be installed using package managers like pip. Some popular third-party libraries include:
- NumPy: For numerical computing.
- pandas: For data manipulation and analysis.
- Matplotlib: For data visualization.
- TensorFlow: For machine learning.
- Django: For web development.
You can find a list of Python packages here.
Creating Your Own Modules
Modules help break down large programs into smaller, more manageable pieces. You can create your own modules by defining functions, classes, and variables in a Python file.
For example, let's say you have the following directory structure:
| mymodule.py | |
|---|---|
| main.py | |
|---|---|
When you import your own modules from another file, Python searches the same directory, plus entries on sys.path / PYTHONPATH and any installed packages. The simplest case — both files in the same directory — works without extra configuration.
Setting Up a Directory as a Package
Since Python 3.3 (PEP 420), a directory can be a namespace package without __init__.py, but including an (even empty) __init__.py is still the clearest convention and required by some tools. For example, let's say you have a directory named mypackage with the following structure:
To import the mypackage directory as a package, you can leave __init__.py empty (or add package initialisation code), then import submodules explicitly:
| main.py | |
|---|---|
Summary
Modules allow you to import different pieces of code and structure large projects.