Modules
Har .py file khud ek "module" hai — kisi doosri file se uske functions/classes/variables import kar sakte ho. import module_name poora module import karta hai, from module_name import thing sirf specific cheez import karta hai.
if __name__ == "__main__": ek bahut common Python pattern hai — is block ke andar ka code SIRF tab chalta hai jab file directly run ki jaaye (python file.py), na ki jab kisi doosri file se import ki jaaye. Isse test code aur reusable code alag rehta hai.
# math_utils.py:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
if __name__ == "__main__":
print("Ye sirf tab chalega jab math_utils.py directly run ho")
# main.py:
import math_utils
print(math_utils.add(5, 3)) # 8
from math_utils import subtract
print(subtract(10, 4)) # 6
import math_utils as mu # alias
print(mu.add(1, 2))- Har .py file ek module hai, import se access karo
- from x import y = specific cheez, import x = poora module
- if __name__ == "__main__": = "directly run hua" check
Package ek folder hai jisme multiple modules hon, plus ek __init__.py file (jo Python ko batati hai "ye folder ek package hai"). Bade projects mein related modules ko packages mein group karte hain — jaise ek "utils" package jisme string_utils.py, math_utils.py ho.
# Folder structure:
# myapp/
# __init__.py
# utils/
# __init__.py
# string_utils.py
# math_utils.py
# Import karna:
from myapp.utils import string_utils
from myapp.utils.math_utils import addAbsolute import poora path specify karta hai project root se (from myapp.utils import helper). Relative import current module ke relative hai (from .utils import helper, . = same package). Absolute imports usually zyada clear aur recommended hain.
# Absolute (recommended, clearer):
from myapp.utils.string_utils import capitalize
# Relative (package ke andar se hi use ho sakta hai):
from .string_utils import capitalize # same folder
from ..utils import string_utils # parent folder