19

So I start up pyscripter and I get a file with this in it:

def main():
    pass

if __name__ == '__main__':
    main()

What is that? Why does my program work without it as well? Whats the purpose for this anyway? Where would my code go? Lets say a a function that prints hello world. Where would that go? where would I call it?

2
  • why is this getting upvotes with all those duplicates?
    – none
    Nov 10, 2012 at 16:47
  • 2
    Because this question covers a very wide range of sub-questions books dont detail about nor do the other questions you pointed out above
    – user836087
    Nov 10, 2012 at 17:14

5 Answers 5

17

The purpose is basically that you can define a central entrypoint, if, and only if, the script is directly run on its own. Because __name__ will only ever be equal to '__main__', if it is run on its own. Putting your script’s actual content into a separate function allows other scripts to import said function and run it whenever they want it, so it won’t run immediately when the script is imported.

This is also often used in libary modules to have some default behaviour when you just need something quickly. For example the http.server module offers a wide functionality to create your own HTTP server with whatever features you can think of. If you just want to quickly have a simple server listen and pass files statically, you can just use the module’s default behaviour when run from the command line.

Running python3 -m http.server on the command line will exactly do that; run the http.server module, which itself will start a simple HTTP server in its __name__ == '__main__ block.

In response to your comment:

For normal modules, that act as libraries, contain types or functions, your application needs, you don’t need a main function or main block. For scripts that are called directly, for example your starting script that actually launches your application you will have some kind of code that is not encapsulated in functions or classes but that runs directly. That would be something, you could put in a main function which you then call separately. This gives you a bit more freedom to where you put that code. For example you can have the main function directly at the beginning of the file, while additional functions that are called within it are defined further into the file. And the very last part of the script is then the main(). You don’t necessarily need to put that into a if __main__ == '__main__': condition, you could just call it directly. So for example your script could look like this:

def main ():
    # doing something
    utilityFunction(...)
    otherUtilityFunction(...)

def utilityFunction (...):
    ...
def otherUtilityFunction (...):
    ...

main()

If you don’t put the code into a separate function, you’d have to do all the processing at the bottom (after your function definitions) and that might be counter-productive if you just want to quickly see what you do when the script is directly called.

Now, as I said, you don’t need to put that into main-condition block; you can just call it directly. However, if for whatever reason you ever need to include that file, for example because you want to encapsulate it into some other thing, or if you want to call it repeatedly from an interactive shell (IDLE or something), you probably don’t want to run main() whenever you just import the module but only when you want to actually execute its functionality. That’s where you should put the main() into the condition; that way it won’t get executed unless you are directly executing the module.

In general, it’s not a bad idea to always put the main() call into such a condition, as it will never hurt but often turn useful at some later point.

4
  • 2
    You make the assertion that __name__ will only ever be equal to __main__ if it's run from the command line. While the essence is true, it's not strictly fact, it is possible to run that code from within a python script, that said, it's the kind of thing you would have to explicitly try to do. (E.g: with imp.load_module()). Nov 10, 2012 at 16:42
  • @Lattyware Good point, amended my answer.
    – poke
    Nov 10, 2012 at 16:44
  • Poke. I dont get it. When should I have a main block in my code and when shouldnt I? Lets say I have 20 python file dependencies, a large program. Where is main's significance there?
    – user836087
    Nov 10, 2012 at 17:35
  • Added some more things to my answer; didn’t fit into the comment after all ;)
    – poke
    Nov 10, 2012 at 17:49
4

The __name__ global is set to __main__ when you execute a python file, while when you import the file it is set to it's name.

That construct allows you to execute some code only if the file is executed. For example if you have the file mymain.py:

def main():
    print('Hello, World!')


if __name__ == '__main__':
    main()

You obtain this results:

$ python mymain.py
Hello, World!
$ python
Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mymain    # main() *not* executed
>>> mymain.main()
Hello, World!

It's often useful to being able to import a file without having code executed. In this way the main function can be called by third party software without having to create a new process and allowing them to change some things before running it.

So, it is not necessary but it is good practice to use it. Often you'll realize that some functions/classes of a program could be useful by an other program, so being able to import a file without having the main program be executed is good practice.

Comparing to Java having an if __name__ == '__main__': block is like having a class that has only a main method and uses other classes to do his job, while not using it is like having a main method inside a class that also provide other functionality(e.g. some kind of Container or whatever with also a main method that executes the main program).

2

Everything in Python is a statement, there's no such thing as a declaration (for example, a def is a statement creating a function object and binding it to a name). Importing a module means (after some bookkeeping) executing the statements in the module. Likewise, executing a Python file means importing it as module. Hence, just writing a program as module level statements works.

But of course, this is not reusable. When the "program" should also be importable for other modules, you put it in a function (and there are a few other, minor advantages too). But then executing the file (python file.py) wouldn't do anything but defining that function.

Enter __name__, which is the module name and equal to '__main__' for the "entry point" module. So the condition checks if the module was imported or run as script, and does its job in the latter case.

0

You don't actually need this trick for "Hello world", but it is useful in case you are writing a module. The if __name__ == '__main__' clause would make it run main() only if the script is executed directly, and not if used as an import from another script.

0

The idea is quite simple : you can use the file both as a package (something to import somewhere) or as a pure script. If the file is used as a script, the Python's interpreter variable "__name__" contain "__main__" instead of the name of the package.

So, there we test if the __name__ is setted to __main__, which mean we are in script mode, and if yes, we execute the code in the "if" block.

You have to understand a major difference between Java and Python : in Python, when the interpreter read a file, it is executed --> both declaration and code are interpreted, and many features of Python are based upon that.

Not the answer you're looking for? Browse other questions tagged or ask your own question.