Python name == 'main'
def main():
# program code
if __name__ == "__main__":
main()
name क्या है?
Python अपना कोई भी code चलाने से पहले हर module को स्वतः built-in variable __name__ assign करता है -- जब आप किसी file को सीधे 'python script.py' से चलाते हैं, तो उस file का __name__ खास string __main__ पर set हो जाता है।
उदाहरण: What is name?
print(__name__)
Main Guard
अपनी script के entry-point logic को 'if __name__ == "__main__":' में लपेटने का मतलब है कि वह code तभी चलेगा जब file सीधे execute की जाए, न कि जब कोई दूसरी file उसे import करे -- यह किसी file को एक साथ चलने योग्य script और सुरक्षित रूप से import करने योग्य module दोनों बनाने का standard तरीका है।
उदाहरण: The Main Guard
def main():
print("Running main logic")
if __name__ == "__main__": # only runs when this file is executed directly
main()
Modules Import करना
जब किसी file को सीधे चलाने की बजाय import किया जाता है, तो Python उसका __name__ __main__ की बजाय module के अपने नाम (जैसे mymodule) पर set कर देता है -- import किए गए module और उसे import करने वाली script, दोनों के अंदर से __name__ print करना यह अंतर साफ़ दिखाता है।
उदाहरण: Importing Modules
# When this file is imported, __name__ becomes its module name
# instead of "__main__"
print(__name__)
Script बनाम Module
Main guard ही वह चीज़ है जो एक ही file को दूसरे code के import करने के लिए reusable functions और classes define करने देती है, साथ ही नीचे एक runnable demo या test block भी शामिल करने देती है जो तभी चलता है जब कोई उस file को सीधे चलाए, न कि उसे import करे।
उदाहरण: Script vs Module
def greet():
print("Hello from a reusable function")
if __name__ == "__main__":
greet() # only runs when this file is executed directly
Best Practices
top-level code (जो किसी function के अंदर नहीं है) को कम से कम रखना और असली logic को main guard के अंदर से call किए गए functions में ले जाना, variable names को module के namespace में लीक होने से रोकता है और file के व्यवहार को समझना आसान बनाता है।
उदाहरण: Best Practices
def run():
print("Logic lives inside a function") # keeps names out of the module's top-level namespace
if __name__ == "__main__":
run()
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: