7

I have been learning Python and as a person with Java and C# background I can understand why we need to use main method in those languages but I don't quite get it for Python. I can easily get what I want without writing a class or if I want to import or write module, it doesn't have to have any class defined within at all.

As an entry point a simple myFunction() call would be sufficient as the first statement and I can define this method in the following lines and I can have that method do the initialization and so on.

About the statements above, please correct me if I am wrong but if I have all these easy things what would I need to have use main method after all?

Tarik
  • 79,711
  • 83
  • 236
  • 349
  • http://stackoverflow.com/questions/5544752/should-i-use-a-main-method-in-a-simple-python-script – kgu87 Oct 24 '13 at 23:11

3 Answers3

13

There isn't really a main method in Python, but rather a main guard, i.e., a test to see if the module is the entry point to the script/program. This looks like:

if __name__ == '__main__':
     # your code

Having a main guard clause in a module allows you to both run code in the module directly and also use procedures and classes in the module from other modules. Without the main guard clause, the code to start your script would get run when the module is imported.

corriganjc
  • 660
  • 7
  • 21
4
def main():
   #blah blah 

is just a convention you absolutely can name it whatever you want

the

if __name__ == "__main__":
    some_function()
    or_some_commands()

is the important part that only runs if your script is the main entry point to the program

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
3

To put it in simpler terms, __main__ is simply a way to test if the program running is the main program.

For example, you could write an entire program and call all your functions in that program:

def f1(x):
    #code

def f2(x):
    #code

.
.
#etc

f1(x)
f2(x)
.
.
#etc

The problem with this, is what if you imported this program as a module, and didn't want certain functions to be called when it is a module? That's the purpose of __main__.

So if you wanted f1 to run always, and f2 to only run if it is not imported as a module, you would type this if statement:

f1(x)

if __name__=='__main__':
    f2(x)
samrap
  • 5,595
  • 5
  • 31
  • 56