Python is a powerful programming language that allows us to write clean and efficient code. However, writing large programs from scratch every time is not practical. This is where Python modules come in.
A Python module is a file containing Python code (functions, variables, or classes) that can be reused in other programs. Modules help organize code, making it more manageable and reducing repetition. In this article, we will explore Python modules, their types, how to use them, and several practical examples.
Learn Also: Parameter Handling: *args and **kwargs in Python
What Exactly is a Python Module?
A Python module is a .py
file that contains Python code. It can include functions, variables, classes, and even other modules. Any Python file can be considered as a module. For example, if you have a file named my_helper.py
, then my_helper
is the name of the module.
Imagine you are a mechanic who needs different tools to fix a car. Instead of making new tools every time, you use a toolbox where all tools are organized. Similarly, Python modules work as a toolbox for programmers, containing reusable code.
How to Use Python Modules
You have to use the import
keyword to import a module in Python.
Import a Built-in Module
The math
module provides various mathematical functions stored inside. Let’s import this:
import math print(math.sqrt(25)) # Output: 5.0 print(math.factorial(5)) # Output: 120
Here, we import the math
module and use its two functions sqrt()
and factorial()
.
Create and Import a User-Defined Module
Let’s imagine we have a module named greeting.py
with the following content:
message = "Hello there!" def say_hello(name): print(f"{message} Welcome to {name}!")
Now, let’s see how we can use this module in another file, say main.py
.
import greeting print(greeting.message) greeting.say_hello("PySeek")
The import greeting
line imports the entire greeting module in the main.py
. To use anything defined in greeting.py
, you must prefix it with the module name followed by a dot (.
), like greeting.message
or greeting.say_hello()
.
Output
Hello there! Hello there! Welcome to PySeek!
Install and Use Third-Party Modules
Third-party modules are created by other developers and organizations and shared with the Python community. These modules offer a wide range of functionalities, from web development to data science and much more.
Usually, we need to install these modules first using a package manager like pip
(Python’s default package installer).
Installation
Open your terminal or command prompt and type pip install module_name
(e.g., pip install requests
).
Example
import requests response = requests.get("https://api.github.com") print(response.status_code) # Output: 200 (if successful)
Types of Python Modules
Python modules are categorized into three types:
Built-in Modules
Built-in modules are pre-installed with Python and provide a wide range of functionalities. Examples:
math
: For mathematical operationsrandom
: For random number generationos
: For interacting with the operating systemdatetime
: For working with dates and timessys
: For accessing system-specific parameters and functions.
User-defined Modules
These are the modules we create for our own projects, like the greeting.py
example above.
You simply create a .py
file, write your Python code in it, and then import it into another script (usually one located in the same directory).
Third-party Modules
These modules are not included with Python by default but can be installed using pip. Here are some examples:
numpy
: For numerical computingpandas
: For data analysisrequests
: For handling HTTP requests
Advanced Concepts in Python Modules
Import Specific Functions from a Module
You can import only specific functions from a module using the namespace from
. Let’s see an example:
from math import sqrt, factorial print(sqrt(49)) # Output: 7.0 print(factorial(4)) # Output: 24
from math import sqrt, factorial
imports only sqrt
and factorial
into your main.py
. In this case, you can use sqrt
and factorial
directly, without the module name prefix.
Import with an Alias (Nickname)
If the module name is long or you just prefer a shorter name, you can give it an alias using as
.
import math as m print(m.sqrt(36)) # Output: 6.0
Import Everything
You can import everything from a module using *
.
from math import * print(sqrt(49)) # Output: 7.0 print(pow(7, 3)) # Output: 343.0
from math import *
imports all the functions from the math
module. In this case, you don’t have to use the module name as a prefix or import some specific functions separately.
Important Note: This technique should be avoided in larger projects. It makes it very hard to know where a specific function or variable came from. So, it can easily lead to naming conflicts (overwriting existing names in your script without warning) and makes the code less readable and harder to debug.
Get the List of Available Functions in a Module
To see all functions available in a module, we use the dir()
function.
import math print(dir(math))
Output
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'exp2', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'sumprod', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
Check Module Documentation
You can view the documentation of a module using the help()
function.
import math help(math)
How Does Python Find Modules?
When we write import my_module
, how does Python know where to look for my_module.py
? It searches in a specific order:
- The directory that contains the input script (or the current directory if running interactively).
- Directories which are listed in the
PYTHONPATH
environment variable (if set). This is an optional list of directory paths you can define. - Installation-dependent default paths. This includes those locations where Python and third-party packages are installed (like the
site-packages
directory).
Python stores this search path in a list called sys.path
. You can actually view it:
import sys print(sys.path)
Going Further: Python Packages
What if you have many related modules? For example, modules for reading different file types, and others for processing data. Putting them all in the root directory might become messy again.
This is where packages come in. A Python package is simply a way to structure Python’s module namespace by using “dotted module names”.
A package is essentially a directory that contains:
- One or more module files (
.py
files). - Possibly other sub-package directories.
- A special file named
__init__.py
(can be empty, but must exist to tell Python the directory is a package).
For example, you could have a structure like this:
my_project/ |-- main.py |-- data_tools/ | |-- __init__.py | |-- reader.py | |-- processor.py | |-- utils/ | | |-- __init__.py | | |-- helpers.py
Now, from main.py
, you could import like this:
import data_tools.reader from data_tools.processor import process_data from data_tools.utils import helpers data_tools.reader.read_file(...) process_data(...) helpers.some_utility(...)
Packages allow us to create a hierarchical structure for our modules and make it easier to manage very large projects.
Summary
Python modules are powerful tools to write clean, organized, and efficient Python code. Whether you’re using built-in modules, third-party modules, or user-defined modules, they make Python programming easier and more efficient. In this tutorial, we learned:
- What are Python modules
- How to use them in the main code
- Types of Python modules
- Additional Concepts related to Python modules, etc.
So, start organizing your code into modules today – your future self will thank you!
Do you have any questions about this topic? Reach out to me at contact@pyseek.com. 😊
Happy Coding!