Two variations of the main Python function

When writing scripts for personal use, I got used to 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 that the first form is useful in differentiating between importing a script as a module or calling it directly, but otherwise for scripts that will be executed (and never imported), is there any reason to prefer one of them to the other?

+5
source share
2 answers

Even if the script is intended only for execution, it can sometimes be useful to import it - in an interactive shell, by means of creating documentation, in unit tests or for performing timings. Therefore, the usual use of a more general form will never hurt.

+17
source

- . , - (, , ), " " script, , - .

, - ( ?), , - .

- , , - , , , , , .

!

+4

All Articles