They allow you to divide your program into multiple files and reuse functionality across projects.
What is a Module?
A module is a Python file that contains functions, classes, and variables you can reuse in other programs. Modules help structure your code logically. Example:Let's create a file named math_utils.py:
# math_utils.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
Now, you can import and use this module in another file:
# main.py
import math_utils
print(math_utils.add(5, 3)) # Output: 8
print(math_utils.multiply(4, 6)) # Output: 24
Here, math_utils is a module.
Importing Modules
There are different ways to import a module in Python.| Syntax | Description |
|---|---|
| import module_name | Imports the entire module |
| from module_name import function_name | Imports specific functions |
| from module_name import * | Imports all functions (not recommended) |
| import module_name as alias | Imports a module with a short name |
import math
print(math.sqrt(16)) # Output: 4.0
from math import pi, sqrt
print(pi) # Output: 3.141592653589793
import math as m
print(m.factorial(5)) # Output: 120
The __name__ == "__main__" Construct
In Python, every file (module) has a built-in variable called __name__. When you run a Python file directly, Python automatically sets __name__ to "__main__".When you import that same file into another Python file, __name__ is set to the moduleβs name, not "__main__".
In simple words:
- If the file is being run directly, __name__ == "__main__" β True
- If the file is being imported, __name__ == "__main__" β False
This allows us to write code that behaves differently when imported vs executed directly. Example:
#main_program.py
def greet():
print("Hello from greet()!")
if __name__ == "__main__":
print("Running directly...")
greet()
else:
print("Running via import...")
Case 1 β Run directly:
python main_program.py
Output:
Running directly...
Hello from greet()!
Case 2 β Import into another file:
#import_test.py
import main_program
python import_test.py
Output:
Running via import...
Why it's useful?
It allows you to separate reusable code from execution code. You can write:- Functions, classes, and reusable logic (importable anywhere)
- And still test them in the same file safely
Real-life pattern:
def main():
print("Program starts here!")
if __name__ == "__main__":
main()
Ensures main() runs only when the file is executed, not when itβs imported by another module.
Built-in Modules
Python comes with a rich collection of built-in modules that make development faster and easier. Some popular ones include:| Module | Purpose |
|---|---|
| math | Mathematical operations |
| datetime | Date and time handling |
| os | File and directory management |
| sys | System-specific parameters and functions |
| random | Random number generation |
| json | JSON data handling |
| re | Regular expressions |
import datetime
today = datetime.date.today()
print("Today's date:", today)
What is a Package?
A package is a collection of multiple Python modules grouped together in a directory. Every package must contain a special file named init.py (can be empty) β it tells Python that the directory should be treated as a package.Example: Directory Structure
my_package/
__init__.py
calculator.py
converter.py
#calculator.py
def add(a, b):
return a + b
#converter.py
def km_to_miles(km):
return km * 0.621371
Using the package:
#usage.py
from my_package import calculator, converter
print(calculator.add(5, 3)) # Output: 8
print(converter.km_to_miles(10)) # Output: 6.21371
You can import individual modules or specific functions from a package:
from my_package.calculator import add
print(add(10, 20))
Or import all modules inside a package (using all inside init.py):
__all__ = ['calculator', 'converter']
In Python packages, the special variable __all__ (defined inside a package's __init__.py file) controls what gets imported when someone uses:
from package_name import *
Only the modules listed in __all__ β i.e. calculator and converter β will be imported automatically.
Advantages of Using Modules and Packages
- Code Organization β Divide large projects into logical units.- Reusability β Write once, use multiple times across applications.
- Maintainability β Easy to update or fix parts of a project.
- Namespace Management β Avoid variable/function name conflicts.
- Testing β Individual modules can be tested separately.
Summary
Modules and Packages form the backbone of structured Python programming. They help you write cleaner, modular, and scalable applications.| Concept | Description |
|---|---|
| Module | A Python file (.py) containing reusable code |
| Package | A directory containing multiple modules |
| import | Used to bring external code into your program |
| __init__.py | Marks a directory as a package |
| __name__ == "__main__" | Checks if a file is run directly or imported |
| Built-in Modules | Pre-installed modules in Pythonβs standard library |