The __name__ == "__main__" construct in Python is a common pattern used to determine whether a Python script is being run as the main program or if it is being imported as a module into another script. This check is often used to control the execution of code that should only run when the script is executed directly.
We have two .py files.
File 1: sample.py
print('This is sample.py code')
def print_sample_text():
print('This is a sample text')
# __name__ is in-built variable
if __name__ == "__main__":
print('Sample.py is executed directly')
else:
print('Sample.py is imported')
print(f"Its name is: {__name__}")
File 2: demo.py
import sample
sample.print_sample_text()
if __name__ == "__main__":
print('demo.py is executed directly')
else:
print('demo.py is imported')
print(f"Its name is: {__name__}")Now, if we run sample.py, output will be like:This is sample.py code Sample.py is executed directlyIf we run demo.py, output will be like:This is sample.py code Sample.py is imported Its name is: sample This is a sample text demo.py is executed directlyNow, notice the highlighted line. It should be executedonly when we are running sample.py. But it is getting executedwhile import. Lets move this to the if block.# print('This is sample.py code')
def print_sample_text():
print('This is a sample text')
# __name__ is in-built variable
if __name__ == "__main__":
print('Sample.py is executed directly')
print('This is sample.py code')
else:
print('Sample.py is imported')
print(f"Its name is: {__name__}")
Now, the output is:
Sample.py is imported
Its name is: sample
This is a sample text
demo.py is executed directly
No comments:
Post a Comment