- cross-posted to:
- programmerhumor@lemmy.ml
- cross-posted to:
- programmerhumor@lemmy.ml
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?
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?
I remember how weird this looked the first time I saw it and while I may now understand it, it still looks jank af
Python: I’m so readable that I’m practically executable pseudo-code
Also Python:
if __name__ == '__main__':
. . .I still wonder why.
unless it’s for something that you want to work as an importable module and a standalone tool, then why do you need that?
The main two reasons that I can think of to include this even when you have no intention of importing this as a library are:
This is exactly why the conditional is used. It allows the script to function both as a standalone application and a library.
ETA: Probably would make sense to just treat it as default behavior in the interpreter and only require the conditional to overwrite in cases where
main
is not the main function and/or pre-processing is needed.Oh that is a good point actually. It’s been a while since I have done any serious Python, so I’m not sure why you couldn’t just use convention instead of this conditional.
For my part, if a Python script is meant to be executed, then I’ll give it a shebang, drop the .py, and simply mark it as executable in the filesystem. 🤷♂️
Now think about this, you have logic that doesn’t make sense when run directly, but you need it to be a library.
You have multiple name=main statements in some of your functions
I’m not sure I’m following the implication. Name=main is for scripts primary, is it not?
I’ve never thought to add more than one of these conditionals anyway…
So you might have a script that does stuff as a library, and it should get environment variables and other info from the calling script. You use the same script for doing one off stuff on different computers.
So you make it do something slightly different or make it set it’s path and look into the current folder when you run it directly. This change in logic could be in a few points in the script.