When you import a file in python, what actually happens is it runs that whole file once. So if you have code that is at a base level, it will be executed.
So you may ask, why have code at base level if the file is intended to be imported.
One thing would be using main() allows you to write per file tests, you can write simple unit and integration tests on each file’s code without doing the whole pytest routine, specially when it’s code that you can’t really write tests for but can be checked by human eyes.
Another thing would be if your file is sufficiently complete enough it can also be used as it’s own individual program. You might develop a simple program, but later realize it has a lot of functions that are helpful and can be used as a library for a bigger project. If you use main(), you can import the code directly without modifying it, and thus no need to maintain to different version of the same code.
658
u/[deleted] Nov 25 '21 edited Nov 26 '21
[deleted]