r/learnpython • u/pedrinjose • 11d ago
Basically, if main
In Python, when you run your program in another folder, we add this, but I don't understand why. What's the point of doing this? If someone could explain it in a simplified way, I'd appreciate it.
10
Upvotes
View all comments
4
u/Successful_Noise_347 11d ago
easiest way to see it: make utils.py with a function and a couple of test prints at the bottom. then in app.py do import utils. run app.py and the test prints fire, because importing a file runs the whole thing top to bottom
wrap those prints in if name == "main": and now they only run when you do python utils.py yourself, and stay quiet when another file imports it. that's the entire trick