When Python runs a file, it sets a special variable __name__. If you run the file directly (python tool.py), __name__ is "__main__". If another file imports it (import tool), __name__ is the module's name, "tool".
So this block runs only when the file is executed directly:
def main():
print("running")
if __name__ == "__main__":
main()
It is not required, but it is a good habit. Without it, importing your file to reuse one function would also run all your top-level code, such as starting a download or printing output.
Put definitions at the top, and put the "do something" code inside main(), called from the guarded block. This also makes the file easy to test.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
When Python runs a file, it sets a special variable
__name__. If you run the file directly (python tool.py),__name__is"__main__". If another file imports it (import tool),__name__is the module's name,"tool".So this block runs only when the file is executed directly:
It is not required, but it is a good habit. Without it, importing your file to reuse one function would also run all your top-level code, such as starting a download or printing output.
Put definitions at the top, and put the "do something" code inside main(), called from the guarded block. This also makes the file easy to test.