4 ms·
There's a big benefit to Python's convention if __name__ == "__main__": ... especially in contrast with c and other languages that shoehorn you into d
by klyrs 6y ago
There's a big benefit to Python's convention
if __name__ == "__main__":
...
especially in contrast with c and other languages that shoehorn you into defining a main function. Namely, you can put a "main" into a module, and import that into another module without causing trouble.
I use this a lot during a development cycle (not so much in prod). Say I'm trying to replace a function foo with a new implementation foo_new in a large package. I write some rudimentary tests and benchmarks in "main" which compare the two methods (including a late-import of the top-level package), and directly execute that file until I'm satisfied. At that point, I'll switch (foo, foo_new) -> (foo_old, foo) and start running unit tests. Once those unit tests pass, I remove "main" (usually, promoting some fragments of it to new unit tests) and foo_old.
- uryga 6y ago> especially in contrast with c and other languages that shoehorn you into defining a main function i don't think that's a problem in languages with namespaces/modules -- a module might define a main(), it just wouldn't be used when it's imported. (unless you're in C, then you'd get a name clash)