Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is the __name__ == '__main__' idiom used for? __name__ == '__main__' idiom किस लिए इस्तेमाल होता है?

Answer

This idiom lets a Python file work both as a standalone script AND as an importable module, by checking whether the file is being run directly or imported elsewhere.

# calculator.py
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def main():
    print(add(2, 3))
    print(subtract(5, 2))

if __name__ == '__main__':
    main()  # only runs when calculator.py is executed DIRECTLY

# Running directly:
# python calculator.py
# Output: 5, 3 (main() runs)

# Importing it elsewhere:
# other_file.py
import calculator
print(calculator.add(10, 20))  # 30
# main() does NOT run here - just the add/subtract functions are used

# Why __name__ is different in each case:
# - When a file is run directly, Python sets its __name__ to '__main__'
# - When a file is imported, Python sets its __name__ to the module's actual name
print(__name__)  # '__main__' if run directly, 'calculator' if imported

# This pattern is essential for writing testable, reusable modules -
# it lets you put demo/test code in the same file without it running
# every time the module's functions are imported elsewhere

यह idiom Python file को standalone script और importable module दोनों की तरह काम करने देता है, यह check करके कि file directly चलाई गई है या कहीं और import हुई है।

# calculator.py
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def main():
    print(add(2, 3))
    print(subtract(5, 2))

if __name__ == '__main__':
    main()  # सिर्फ directly चलाने पर

# Directly चलाना:
# python calculator.py

# कहीं और import करना:
import calculator
print(calculator.add(10, 20))  # 30
# main() यहां नहीं चलता

print(__name__)  # directly चलाने पर '__main__', import होने पर module का नाम

# यह pattern testable, reusable modules लिखने के लिए essential है

Was this answer clear?