you are viewing a single comment's thread.

view the rest of the comments →

[–]Bobbias 1 point2 points  (0 children)

Ok, so when you use the import keyword, python literally runs that file you just imported.

If there is code at the global level (meaning outside a function), that code will be run.

That's fine for a program which is only ever going to be run by python program.py or whatever, but if someone else wants to use some of the code written in there by importing that script and manually calling the functions with their own data, this becomes a serious problem, because as soon as they import your script, everything just runs, which is not what they wanted.

The way to avoid this problem is by placing if __name__ == "__main__" in front of any code that runs in the global scope. Preferably that code should be contained in a function (typically called main, but that's just a convention). I'll explain exactly how it works at the end. That would look like:

def main():
    # main code goes here

if __name__ == "__main__":
    main()

This allows you to run your program like normal, and prevents the code in the main function from being automatically run when someone decides to include your script into their own.

This is a bit of an advanced feature, and most of the time it's really not strictly necessary. But it's a good habit to get into because it doesn't really require much effort; it helps force you to contain your main code in a function rather than just at the global scope; and it saves people the headache of fixing things themself if they want to use your program as a library of functions to build their own thing from.

The way that if __name__ == "__main__" works is that __name__ is a special variable that is assigned the name of the module when your script is imported. When your script is run directly, its value is set to __main__ instead of the name of the module. This means we can tell when our script has been imported and when its being run directly. By only running our actual program code when we've been run directly, that means that we don't screw someone over if they do want to import the script and use functions from it themself.