← Back to Python Course | Chapter 8: Modules & Packages | Lesson 6 of 6

Python name == 'main'

यह खास जाँच Python को बताती है कि कोई file सीधे चलाई जा रही है या किसी दूसरी file द्वारा उधार ली गई है, जैसे यह पूछना कि आप main performer हैं या सिर्फ़ guest। यह code को गलत समय पर चलने से रोकती है।
Syntax
python
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?

python
print(__name__)

Main Guard

अपनी script के entry-point logic को 'if __name__ == "__main__":' में लपेटने का मतलब है कि वह code तभी चलेगा जब file सीधे execute की जाए, न कि जब कोई दूसरी file उसे import करे -- यह किसी file को एक साथ चलने योग्य script और सुरक्षित रूप से import करने योग्य module दोनों बनाने का standard तरीका है।

उदाहरण: The Main Guard

python
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

python
# 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

python
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

python
def run():
    print("Logic lives inside a function")  # keeps names out of the module's top-level namespace

if __name__ == "__main__":
    run()
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.