Python Modules परिचय
In this page:
Module क्या है?
एक module बस एक .py file होती है जिसमें functions, classes, या variables होते हैं -- एक बार जब आप 'import mymodule' करते हैं, तो उस file के top level पर define हर चीज़ mymodule.something के रूप में सुलभ हो जाती है, इसी तरह Python बड़े programs को organized, reusable files में तोड़ती है।
उदाहरण: What is a Module?
import math
print(math.sqrt(16))
name Variable
Python हर module का __name__ __main__ तभी set करता है जब वह file सीधे चलाई जाती है (python script.py), लेकिन जब वह कहीं और import की जाती है तो उसे file के अपने नाम पर set करता है -- यही अंतर आम 'if __name__ == "__main__":' guard के आधार का काम करता है।
उदाहरण: The name Variable
print(__name__) # "__main__" when this file is run directly
if __name__ == "__main__":
print("Running directly")
Memory में Modules को Mock करना
types.ModuleType आपको disk पर किसी corresponding .py file के बिना, memory में एक module object बनाने देता है, जो एक niche लेकिन असली technique है जिसका उपयोग testing frameworks में होता है जिन्हें filesystem को छुए बिना किसी import को fake करना होता है।
उदाहरण: Mocking Modules in Memory
import types
fake_module = types.ModuleType("fake_module") # builds a module object with no .py file behind it
fake_module.greet = lambda: print("Hi from fake module")
fake_module.greet()
Active Modules Directory
किसी run के दौरान Python ने जो भी module पहले ही import कर लिया है, वह sys.modules dictionary में cache हो जाता है (ताकि वही module फिर से import करने पर उसका code दोबारा execute न हो), जबकि sys.path उन directories की सूची है जिन्हें Python किसी नए import को resolve करते समय खोजता है।
उदाहरण: Active Modules Directory
import sys
import math
print("math" in sys.modules) # already-imported modules are cached here
print(len(sys.path) > 0) # directories Python searches for imports
Modules को Reload करना
importlib.reload(module) किसी module का code फिर से चलाता है और उसके namespace को जगह पर ही update कर देता है, जो किसी file को edit करने के बाद लंबे समय तक चलने वाले REPL session में कभी-कभी उपयोगी होता है -- हालाँकि reload से पहले बने पुराने objects के मौजूदा references अपने आप update नहीं होते।
उदाहरण: Reloading Modules
import importlib
import math
importlib.reload(math) # re-runs the module's code and updates its namespace
print(math.pi)
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: