Modules in Python 📦🐍

A module in Python is a file containing Python code (functions, classes, or variables) that can be imported and reused in other programs.
🔹 Modules help organize code into smaller, reusable pieces.
🔹 Any Python file (.py) is a module that can be imported into another script.
1️⃣ Creating and Importing a Module
✅ Creating a Module (my_module.py)
# my_module.py
def greet(name):
return f"Hello, {name}!"
pi = 3.14159
✅ Importing the Module
import my_module
print(my_module.greet("Alice")) # Hello, Alice!
print(my_module.pi) # 3.14159
🔹 Syntax: import module_name
🔹 Access module functions/variables using dot notation (module_name.function()).
2️⃣ Different Ways to Import Modules
✅ 1. Importing the Entire Module
import my_module
print(my_module.greet("Bob")) # ✅ Uses dot notation
✅ 2. Importing Specific Functions/Variables
from my_module import greet, pi
print(greet("Charlie")) # No need for dot notation
print(pi) # 3.14159
🔹 No need for module_name. prefix when using from module import function.
✅ 3. Importing with an Alias (as)
import my_module as mm
print(mm.greet("David")) # Uses alias instead of full module name
✅ 4. Importing Everything (*) ❌ (Not Recommended)
from my_module import *
print(greet("Eve")) # Works without dot notation
print(pi)
🔹 from module import * imports everything, which can cause namespace conflicts.
3️⃣ Built-in Modules in Python
Python comes with many built-in modules (standard library) that provide extra functionality.
✅ Examples of Built-in Modules
import math
import random
import datetime
print(math.sqrt(16)) # 4.0
print(random.randint(1, 10)) # Random number between 1-10
print(datetime.datetime.now()) # Current date and time
🔹 Check all built-in modules using:
help("modules")
4️⃣ Finding Module File Path
To check where a module is located:
import math
print(math.__file__) # Shows the location of math module
5️⃣ Running a Module as a Script (__name__ == "__main__")
Modules can be used both as an import and as an independent script.
# my_module.py
def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
print(greet("Main Script"))
🔹 If my_module.py is run directly, it prints "Hello, Main Script!".
🔹 If my_module.py is imported, the if __name__ == "__main__" block won't execute.
Summary
Import Method Syntax Usage
Import entire module import module_name module_name.function()
Import specific items from module_name import function function() (no module prefix)
Import with alias import module_name as alias alias.function()
Import everything from module_name import * ❌ Not recommended (namespace conflicts)
Date: 2025-03-24 00:00:00.000000