Junior — Middle
Why is the check if __name__ == '__main__' used in Python when running a script?
sobes.tech AI
Answer from AI
In Python, the check if __name__ == '__main__': is used to determine whether the script is being run directly or imported as a module into another script. When the file is run directly, the variable __name__ gets the value '__main__'. If the file is imported, __name__ will be equal to the module's name.
This allows writing code that only executes when the script is run directly, such as tests or demonstration calls to functions, and not executing this code upon import.
Example:
# example.py
def main():
print("Run directly")
if __name__ == '__main__':
main()
If you run python example.py, it will output "Run directly". If you import example into another file, the code inside the block will not execute.