---
title: "What does \"if __name__ == '__main__'\" do in Python?"  
description: "What does \"if __name__ == '__main__'\" do in Python?"  
author: "Arnaud Simon"  
published: 2026-11-15  
updated: 2026-11-15  
canonical: https://www.mindstick.com/forum/163032/what-does-if-name-main-do-in-python  
category: "python"  
tags: ["python", "__name__", "main", "modules", "scripts"]  
reading_time: 1 minute  

---

# What does "if __name__ == '__main__'" do in Python?

Every script I copy has this line at the bottom. Is it required?

## Replies

### Reply by Vaibhav Kumar

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.


---

Original Source: https://www.mindstick.com/forum/163032/what-does-if-name-main-do-in-python

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
