The if __name__ == "__main__": construct in Python is a conditional block that runs only when the script is executed directly, not when it is imported as a module. It lets you write code that serves both as a reusable module and as a standalone program, by separating the executable part from the definitions.
Formula
The formula for average pace is:
pace (min/km) = finish time (min) / distance (km)
Average speed is the inverse, converted to hours:
speed (km/h) = distance (km) / (finish time (min) / 60)
- t = finish time in minutes
- d = distance in kilometers
- pace = minutes per kilometer (lower is faster)
- speed = kilometers per hour (higher is faster)
Worked Example
Using the default values: finish time = 50 minutes, distance = 10 km.
- Pace = 50 / 10 = 5.00 min/km
- Speed = 10 / (50 / 60) = 10 / 0.8333 = 12.00 km/h
So a 50‑minute 10 km run gives an average pace of 5:00 per kilometer and an average speed of 12 km/h.
Why the Construct Exists
Every Python module has a built-in variable called __name__. When you run a file directly (e.g., python script.py), Python sets __name__ to the string "__main__". When the same file is imported by another script, __name__ is set to the module’s name (the filename without .py). The if block checks that variable and only executes the indented code when the file is the main program.
This design lets you put test code, example runs, or command-line interfaces inside the block, while keeping functions and classes available for import without side effects.
How It Works in Practice
Consider a file named calculator.py:
def add(a, b):
return a + b
if __name__ == "__main__":
print(add(2, 3))
- Run directly:
python calculator.pyprints5. - Import elsewhere:
import calculatordoes nothing visible, but you can callcalculator.add(4, 5).
Without the guard, the print would execute on import, which is often unwanted (e.g., in a library or when testing).
Common Use Cases
- Command-line scripts – put argument parsing and the main logic inside the block.
- Testing – include quick self-tests that run only when the file is executed directly.
- Reusable modules – keep the module import-safe while still allowing standalone execution.
- Examples – show usage of functions without forcing side effects on importers.
Common Mistakes and Misconceptions
- Forgetting the guard – code outside the block runs on import, which can cause unexpected prints or errors.
- Using
__name__ == "__main__"in a module that is always imported – the block never runs, so the main logic is skipped. That is usually correct, but if you intended it to run, you need a different structure. - Thinking it is required – it is not mandatory; it is a convention that improves code quality.
- Confusing it with
main()– the construct does not define a function; it is a conditional. Many programmers define amain()function and call it inside the block.
Alternatives and Related Patterns
Some projects use if __name__ == "__main__": main() to keep the entry point clean. Others rely on entry points defined in packaging configuration (e.g., console_scripts in setup.py or pyproject.toml) to generate executable commands. In interactive environments like Jupyter, the construct is less relevant because each cell runs as a script, but it still works.
There is no performance cost to using the guard; it is just a comparison. It is considered best practice for any file that might be imported.
Frequently Asked Questions
What does __name__ equal when running a script directly?
It equals the string "__main__". This is a special value set by the Python interpreter for the file you execute.
What happens if I don’t use the if __name__ == “__main__” guard?
Any code at the top level of the file runs when the file is imported. That can cause unwanted output, slow imports, or errors if the code depends on command-line arguments.
Can I use this construct in a Jupyter notebook?
Yes, but it is rarely needed because each cell is executed directly. However, if you import a notebook as a module (using importlib), the guard prevents the notebook’s main code from running.
Is it the same as defining a main() function?
No. The guard is a conditional that checks __name__. You can call a main() function inside it, but the guard itself does not define a function.
Does the construct work in Python 2 and 3?
Yes, the behavior of __name__ is identical in both versions, and the syntax is the same.
Should I always use it?
It is good practice for any file that might be imported. For small one-off scripts that are never imported, it is optional but still recommended for consistency and future reuse.
Related
Formula used
in t | Finish time | min | 50 | 0 in d | Distance | km | 10 | 0 | 100000 out pace | Average pace | min/km | t / d | 2 out speed | Average speed | km/h | d / (t / 60) | 2
Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.
More cards in this drawer
- Channel TLD Websites: What They Are & How to Get One5.00 min/km
- Django Class Based Views CRUD REST API
- Tmux Terminal Upgrade: Is It Worth It?
- Most Secure OS for Privacy: 3 Picks by Device
- Ryobi One+ Battery System: Is the Switch Worth It?
- Refurbished Tech Buying Checklist