In Python, modules are an essential way to organize and reuse the code. This tutorial will walk us through everything we need to know about Python modules, from basic concepts to advanced usage.
Modules in Python
A module in Python is simply a file containing Python code that can define functions, classes, and variables. This allows us to break up our code into manageable and reusable parts. By creating and using modules, we can make our programs cleaner and more organized. For example, Python’s standard library contains many built-in modules, like math
, os
, and datetime
.
Types of Python Modules
Python provides three main types of modules.
Built-in Modules
These are modules that come pre-installed with Python. We don’t need to install them separately. We can use them directly after the complete installation of Python.
# built-in modules example
import math # math - Python's built-in module
# Using sqrt() function from math module
print(math.sqrt(36)) # Output => 6.0
# built-in modules example
import datetime # datetime - Python's built-in module
# get the current date and time
now = datetime.datetime.now()
print(now) # Output => 2022-10-08 18:17:27.748415
Some popular built-in modules include:
math
– This module provides mathematical functionsdatetime
– This module is used to get date-time and for date-time manipulationos
– This modules is used to interact with the operating systemsys
– Using this module we can provide system-specific parameters and functions
External (Third-Party) Modules
External modules are not part of the standard Python library but can be installed using package manager like pip
. External module examples are numpy
(for numerical computations), pandas
(data analysis), and requests
(HTTP requests).
# First, install the package using pip:
# pip install requests
import requests
response = requests.get('https://shbytes.com')
print(response.status_code) # Output => 200
User-Defined Modules
User defined modules are created by users. They are simple Python files that contain functions and classes we can import into other scripts.
# Python file name - website_info.py
def info(name):
return f"courses@{name}"
# import module and use its function
import website_info
print(website_info.info('shbytes.com')) # Output => courses@shbytes.com
- In this example, we create a Python file (module) with name –
website_info.py
. Addinfo(name)
function in that module - Create another Python script (with any name) to import module and use its function.
import website_info
– This is used to import the module and then we can use its method.
Import Modules
In Python, we can either import an entire module or specific parts of it.
- Import the Entire Module – We can import the entire module using the
import
keyword. e.g.import math
,import datetime
,import sys
# Import the Entire Module
import datetime # datetime - Python's built-in module
now = datetime.datetime.now()
print(now) # Output => 2022-10-08 18:17:27.748415
current_date = datetime.date.today()
- Import Specific Functions or Classes – We can import only specific parts (functions, classes, variables) from a module using
from ... import
. e.g.from math import sqrt, pi
=> This import onlysqrt
andpi
function frommath
module.
# Import Specific Functions or Classes
from math import sqrt, pi
print(sqrt(25)) # Output => 5.0
print(pi) # Output => 3.141592653589793
- Import Everything from a Module – We can import everything from a module using
*
. e.g.from math import *
# Import everything from module
from math import *
print(cos(0)) # Output => 1.0
print(sin(90)) # in radians. Output => 0.8939966636005579
As a best practice, we should import only specific functions, classes or variables that are used from that module. As importing complete module or importing everything can make code less readable and lead to conflicts with other modules.
dir()
Function
dir()
function is used to find out which names (functions, classes, variables) a module defines. This is particularly useful when exploring new modules.
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']
This outputs a list of all the available attributes in the math
module.
Using Aliases with Modules
If the module name is too long or commonly used, we can use aliases to simplify our code by using the as
keyword:
import numpy as np
arr = np.array([12, 22, 35])
print(arr) # Output => [12 22 35]
In this example, we are using import numpy as np
to import numpy
module as
an alias np
.
User-Defined Modules
Creating user-defined modules are easy. Any Python file we create can be imported as a module. Just write the code in a .py
file and import it into Python script.
- Create a module with name –
arithmetic_module.py
# module arithmetic_module.py
def func_add(m, n):
"""return addition of two numbers"""
return m + n
def func_subtract(m, n):
"""return subtraction of two numbers"""
return m - n
def func_multiply(m, n):
"""return multiplication of two numbers"""
return m * n
def func_divide(m, n):
"""return division of two numbers"""
return m / n
- In this example, we have create a module (file) with name
arithmetic_module.py
- This module has defined 4 functions for arithmetic operations.
Use arithmetic_module.py
module in another Python script
import arithmetic_module # module not added multiple times
import arithmetic_module as am # import module with alias
import arithmetic_module
print(arithmetic_module.func_add(3, 4)) # call module function using module name
print(am.func_multiply(3, 4)) # call module function using alias
print(am.func_divide(6, 3)) # call module function using alias
import arithmetic_module
– We are importing the complete module into the scriptimport arithmetic_module as am
– We are importing complete module as an aliasam
- A module cannot be imported multiple times in the same script
arithmetic_module.func_add(3, 4)
– We are calling module functions using the module name itself.am.func_multiply(3, 4)
– We are calling module functions using alias.
Organizing Modules in Packages
A package is a way to organize related modules. A package is a directory that contains multiple Python modules, and it includes an __init__.py
file (which can be empty) to mark the directory as a package.
Package folder structure
# Package folder structure
package_1/
__init__.py
module_1.py
module_2.py
Here, package_1
is a directory which includes module_1.py
, module_2.py
as modules and __init__.py
file to mark the directory as a package. package_1
is a package.
Import modules from package => from package_1 import module_1, module_2
Packaging is good to group similar modules together. This helps in better project organization.
__name__ == "__main__"
Idiom
When a Python file is run directly, the special variable __name__
is set to "__main__"
. This is useful for writing code that behaves differently when a module is run directly versus when it is imported.
# website_info.py
def info(name):
return f"courses@{name}"
# when imported as module, this code will not execute
# when run directly, this code will execute
if __name__ == "__main__":
info("shbytes.com")
When run directly, this script will execute the info("shbytes.com")
function. When imported into another module, the code under if __name__ == "__main__":
won’t be executed.
Best Practices for Writing Python Modules
- Keep it simple – Each module should focus on one logical aspect of program.
- Use descriptive names – Both module and function names should clearly describe what they do.
- Add documentation – Include comments and docstrings to explain your code.
- Version control – Use versioning (such as
__version__
) to keep track of updates to module. - Avoid global variables – Use functions and classes to encapsulate behavior and state
Summary
Modules are a powerful feature in Python that helps keep our code organized, reusable, and maintainable. Understanding how to use both built-in and user-defined modules is essential for becoming proficient in Python. By organizing our code into modules and packages, we can build larger, more modular applications.
In this article, we learned about Modules in Python. Following topics were covered:
Code – Github Repository
All code snippets and programs for this article and for Python tutorial, can be accessed from Github repository – Comments and Docstring in Python.