Python Modules 📦
Code Organization
A module is a file containing a set of functions to include in your application. It allows you to organize your code into separate files.
🧰 Analogy: The Toolbox
Think of a Module as a Toolbox.
- You don't carry every tool you own in your pocket all the time.
- When you need to fix a sink, you grab the "Plumbing" toolbox (Import Module).
- Inside, you find specific tools like a wrench or tape (Functions/Variables).
✨ Creating and Importing
# mymodule.py
def greeting(name):
print("Hello, " + name)
# main.py
import mymodule
mymodule.greeting("Jonathan")🏷️ Aliasing and Partial Imports
Alias (as)
import mymodule as mx
mx.greeting("Jonathan")From Import
from mymodule import greeting
greeting("Jonathan")🎯 Real-World Application: Project Structure
Large projects are split into many modules to keep code clean.
# project/
# ├── main.py
# ├── database.py (handles DB connections)
# ├── auth.py (handles login/signup)
# └── utils.py (helper functions)
# main.py
import database
import auth
database.connect()
user = auth.login("user", "pass")🛠️ Built-in Modules
Python has a rich standard library. You can see all available functions using dir().
import platform
import math
print(platform.system())
print(dir(math)) # List all math functions⚠️ The __name__ Check
When writing modules, it is common to add a check to see if the module is being run directly or imported.
if __name__ == "__main__":
print("This code runs only if executed directly")
print("It does NOT run if imported as a module")✨ Pro Tip: sys.path
If Python cannot find your module, you can check sys.path to see where it is looking.
import sys
print(sys.path)