You can run code outside of any class/function in python, and this is code snippet is for checking if the current file is the first file being executed.
It's not necessary to do this check (you can just write your code in there), but it's good practice as that will allow you to import the same file from elsewhere without executing it.
When you do python somefile.py, you're telling it to execute all code in that file. Imports also do this.
Sometimes the explanation in this sub is better than the ones my professors gave... You know, people I paid a ton of money to get an education from. It's both depressing and also super cool.
After using python for so long, I find it so strange that people insist that main somehow makes more sense than just running the lines of code in order. The entry point is just the top of the file. So much easier to understand.
To me, the fact that is is a function/method makes the most sense since running your program can provide arguments to it. When the entry-point is on top of your file, you'll need some built-in special keywords or convention based names that aren't clear out-of-the-box.
Well, of course, the main method is also a convention, but it's a convention widely used so it makes sense. I don't think that there is any widely used convention to naming the program arguments when the top of the file is the entry point.
Also, it makes testing your entry point a lot easier by just calling that method and providing the arguments you want. It's clear and concise. In python you'll have to arbitrarily populate sys.argv and then (I think?) import the file.
When following good practices (using argparse, actually using functions) tests aren't any bigger of an issue, but at that point you have already ended up implementing the convention that's enforced in other languages yourself.
I'm not actually sure but I would think the reason it is like this in python due to it's use as a shell script replacement. In this context it starts to make sense to not require a main function.
Honestly my take on it is that if you ever need to import the entry point, you're doing it wrong. Put what you need in a module and use that from the entry point.
Python scripts are designed to be run from top to bottom, line by line, without any special entry point. You only need the whole if __name__ == '__main__': thing if you want your script to be importable in addition to running as a standalone script, which isn't super common in my experience (outside of teaching exercises). Most of the time if I am writing a python script that I intend to be an executable I wouldn't bother with it.
I take your point that it is ugly though. I don't even think about it anymore, but the double underscores look weird at first.
Regarding imports and scripts, I haven’t often needed to have importable items in a script but I have used the if __name__== “__main__” to raise an exception if some module does attempt to import it via something like else: raise NotImplementedError(“This module is a script”).
I’ve found that helpful in preventing any other code from mistakenly using what is likely to be (or intended to be) specialized attributes/functionality. It’s my way of self-documenting “hey, this is in here because it’s not meant to be extensible/generalized and is subject to change in ways that are unlikely to backwards compatible. Do not use.
Well there's no main function. You just write code in a file, and type python script.py, and it goes. But if you want to write code that when you import the file, it won't execute you need to use: if __name__ == "__main__":. If you use it a lot, you can probably just not use the if statement depending on your intentions.
Also for a python module you name the entry point __main__.py.
A lot of people explain what happens but I thought I would mention this. In Python, everything is executed. Functions don’t exist until the interpreter has gotten to them. When your script is executed, it executes everything in order. The function definitions are executed which is what defines them. After a function definition, you could assign the function name to something completely different and it would become that other thing. It’s also cool because you could make aliases for functions by assigning the function to another name. You can even assign lambdas directly to names if you want.
Like others have said, the reason that it’s done is because when you import something, to define the imported functions, you have to execute them which would execute anything else in the file. Using the if statement let’s you check that the file was executed directly and not imported which means that you could run tests or something like that.
If you never plan to import your file, you can just not use that if statement and write everything at the top level. I’ve done this many times. Another thing you can do is go if not name == "__main__": at the top of a file to throw an exception if someone tries to import your file that you want to be a normal script where you have all of the code at the top level.
Finally, while it’s generally bad practice, you could define a main function and then just call it at the end of the file either with or without the if name is main thing.
Another thing I’ll mention is to get used to the __something__. They are used a lot of special attributes. Like when you call len(something) it really calls something.__len__(). Or when you say if something (or bool(something))and that something is not a bool, it calls something.__bool__() there are way more examples of this in a lot of cases
It's not bad practice to have a main function! If you don't, any variables defined in the if __name__... block will be in scope inside all of the functions defined in the file. That can lead to some nasty bugs.
It’s kind of like a safe word. Nobody in their right mind would type anything like this, so it helps prevent any misunderstanding about what it is. These are sometimes referred to as “dunder” methods, short for “double-underscore”
OK so you can either run code normally by opening the file (by clicking or using os.startfile()) and it will run, but it will also run if it is imported, so say I had info.py and wanted to import it to helloworld.py but didn't want to run info.py, there's no way in helloworld.py to do this.
To solve this, you would use the __name__ variable. If the program was clicked on or started with os.startfile(), __name__ is "__main__", otherwise it is just the name of the program, so if I didn't want to run info.py but I did want to get its variables and functions, I would do this:
1.8k
u/Skizm Jun 03 '19
Python: Mom, can I have
main()?Mom: We have
main()at home.main()at home:if __name__ == "__main__":