Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two variations of Python's main function

Tags:

python

When writing scripts for personal use, I am used to doing this:

def do_something():
    # Do something.

if __name__ == '__main__':
    do_something()

Or, we can also do this:

def do_something(): 
    # Do something.  

do_something()      # No if __name__ thingy. 

I know the first form is useful when differentiating between importing the script as a module or calling it directly, but otherwise for scripts that will only be executed (and never imported), is there any reason to prefer one over the other?

like image 550
S Singh Avatar asked Jan 25 '12 16:01

S Singh


People also ask

What are two main types of functions in Python?

There are two types of functions in python: User-Defined Functions - these types of functions are defined by the user to perform any specific task. Built-in Functions - these types of functions are pre-defined in python.

What are the various types of functions in Python?

Types Of Python FunctionsPython Built-in Functions. Python Recursion Functions. Python Lambda Functions. Python User-defined Functions.

What are the two main types of functions?

One – one function (Injective function) Many – one function. Onto – function (Surjective Function)

What is the main function of Python?

In Python, the role of the main function is to act as the starting point of execution for any software program. The execution of the program starts only when the main function is defined in Python because the program executes only when it runs directly, and if it is imported as a module, then it will not run.


1 Answers

Even if the script is only meant to be executed, it might sometimes be useful to import it anyway -- in an interactive shell, by documentation generation tools, in unit tests or to perform timings. So routinely using the more general form will never hurt.

like image 116
Sven Marnach Avatar answered Oct 13 '22 11:10

Sven Marnach