Modules and packages help organize your Python code into reusable files and directories. They make your projects manageable, prevent name conflicts, and allow you to share code.
πΉ 1. What are Modules?
A module is simply a Python file (
.py extension) containing Python code (functions, classes, variables).Example:
If you have
my_math.py:# my_math.py
def add(a, b):
return a + b
πΉ 2. Importing Modules
You use the
import statement to bring functionality from one module into another.Syntax:
import module_name
from module_name import specific_item
from module_name import * # Avoid this in large projects
import module_name as alias
Example:python
import my_math
print(my_math.add(5, 3)) # Access function using module_name.function
from my_math import add
print(add(10, 2)) # Access function directly
import math as m # Using an alias for built-in 'math' module
print(m.sqrt(16))
Output:
8124.0πΉ 3. What are Packages?
A package is a way to organize related modules into a directory hierarchy. A directory becomes a Python package if it contains an
__init__.py file (even if empty).Example:
my_project/
βββ main.py
βββ my_package/
βββ __init__.py
βββ graphics.py
βββ sound.py
πΉ 4. Importing from Packages
You import modules or specific items from modules within a package using dot notation.
Example (assuming
my_package above):# In main.py
from my_package import graphics
# Now you can use functions/classes from graphics.py like: graphics.draw_circle()
from my_package.sound import play_effect
# Now you can use play_effect() directly
πΉ 5. Benefits of Modules & Packages
β’ Reusability: Write code once, use everywhere.
β’ Organization: Keeps related code together.
β’ Readability: Easier to understand structured code.
β’ Namespace management: Prevents variable/function name clashes.
π― Today's Goal (What you should do)
βοΈ Understand what modules and packages are
βοΈ Learn how to import functionality
βοΈ Appreciate the benefits of code organization