TGViewer
Python Learning Python Learning @python_bds Β· 5.74K subscribers
Post #1175 697
🐍 Python Modules & Packages (Code Organization) πŸ“‚

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:
8
12
4.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
  • ❀ 4
More from @python_bds
  1. Oct 8, 2026πŸ› This Python Bug Looks Random, But It Isn't Look at this: functions = [] for i in range(…
  2. Oct 6, 2026🐍 Python Performance Optimization Python Performance Optimization: Make Your Code Faster…
  3. Oct 4, 2026Python Set Methods ✍️
  4. Oct 3, 2026Post #1310
  5. Oct 1, 2026🐍 Python Beginner Notes
  6. Sep 30, 2026🧠 return vs print() in Python These are not interchangeable. def add(a, b): print(a + b)…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook β†’Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 β†’