Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit of using main method in Python? [closed]

Tags:

python

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?

like image 345
Tarik Avatar asked Oct 24 '13 23:10

Tarik


1 Answers

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.

like image 125
corriganjc Avatar answered Sep 27 '22 20:09

corriganjc