Also, do y’all call main() in the if block or do you just put the code you want to run in the if block?
Idk, I guess I should ask why python needs a default function? If I’m running it as a script with commandline invocation I just copy and paste the if main namespace thing from stack overflow and it works as I intended. It also works if I invoke via python my_script.py $args, so I don’t really see why I should philosophically care about how other languages that I’m not using do it.
It’s less of a main, and more of a “don’t do this if being imported.” You can just throw code without that block and it will run.
If it’s a quick dirty script like doing a one time update to multiple records then I’ll just write it under the if name == main.
Depends on the situation but since Py3 you now have main.py in Python Packages
I always put all of the code in the main block. Only exception is when I am creating a multithreaded/multiprocessor application. Then I normally use the if statement as the place to setup “the plumbing” with pipes and what not. That way people are forced to realize there is no main function but two co functions working in tandem
if __name__ == '__main__': exec(open(__file__, 'r').read())
It’s a common practice but not required. Python behaves like JS where it just runs whatever you wrote. If you don’t want it to run when importing the file you can put the main() inside the if so it only runs when you run the actual file.
You can use it when developing a function or a class to run a simple test without running the whole program.