+1
Save

The __name__ == '__main__' technique

If you read code from other Pythonistas, you'll notice that you often find that snippet at the end of their programs:

if __name__ == '__main__':
    main()

It might look a bit weird at first but there's a sensible reason why we do that.

First, it's a good idea to kickstart your program from the end of the file. Look at this simple code:

def main():
    spam()
    eggs()

def spam():
    print('Yum! Spam!')

def eggs()
    print('Eggs! Try them with spam!')

main()

Runs without a hitch. But what happens if I start with the call to main first?

main()

def main():
    spam()
    eggs()

def spam():
    print('Yum! Spam!')

def eggs()
    print('Eggs! Try them with spam!')

NameError: name 'main' is not defined

Why? Because at the time we see main(), python didn't see the definition of main yet! And if it did, it couldn't run main, because it doesn't know the definitions of spam() and eggs() yet! So putting it last means that it knows what everything is before starting.

You might wonder why we would want that. Why not just rewrite the thing inside out, start with the helper functions first? The answer is top down programming.

This means, starting with most important stuff first and finishing with the nuts and bolts. Imagine I write a pong game, I could have code like this in it:

def main():
    setup_field()
    setup_controls()
    start_play()

def setup_field():
    setup_paddles()

etc...

If I started with something like draw_rectangles you might wonder why it is there, but if it's called by the function that draws the paddles or the ball, you understand why it's here.

Now, back to the name == 'main' shenanigans.

You probably noticed that it's a weird variable name. In Python, variables with double underscores on both sides are called magic. Magic is things that python does on your behalf without you asking for it directly. It aims to be a low-magic language so when that happens, it puts those underscores to warn you.

The name variable either contains 'main' or the name of the file loaded without the .py part. If you launch a file directly, name is main, if you import it is is the name of the file (also called the module name).

Why do you want that?

Let say you have in your program a program a function called isparrotdead(parrot) (it always returns false). You want to test it so you load your interpreter, do an

import parrot

and your whole program starts because you didn't use the name == 'main' technique!

If anything is unclear, just ask me.

8 years ago by redalastor

Join the Discussion

  • Auto Tier
  • All
  • 1
  • 2
  • 3
Post Comment