The if name == 'main' block

The main block is only run when the file is run directly by Python. When the file is imported, the main block is not run.

Here is one use: put the testing code in the main block, so that when you're importing the file (like you would import math) you can use the functions, but don't see the output of the testing

An important consequence of this is that you must always initialize all global variables outside of the main block.

Here is an example:

program.py

In [1]:
def print_b():
    print(b)



def initialize():
    global a, b
    a = 0
    b = 0


#if you have global variables, you must
#initialize them outside the main block
initialize()

if __name__ == '__main__':
    c = 0       #If you import program elsewhere, 
                #you will not be able to access
                #program.c because the main block
                #will not be executed!
    print(a)
    print(b)
0
0

test_program.py

In [2]:
if __name__ == '__main__':
    import program
    program.print_b()
    print(program.a)
    print(program.b)
0
0
0

import program allows us to use the function and global variables from program.py. Similarly to using math.sqrt(9) or math.py, we can use the function program.print_b() (the function print_b() defined in program.py) and refer to the variable program.a (the global variable a defined in program.py.)

When we say import program, the if __name__ == '__main__' block in program.py is not run. That why only three zeros are printed above (instead of five.)

The global variable c is only defined in the if __name__ == '__main__' block, which means that in test_program.py, we cannot refer to the variable program.c-- this will cause an error.

Things to keep in mind

  • If we want to use a global variable from a file we are importing, that variable must be initialized outside the main block. In program.py, the variables a and b are initialized by called initialize() outside the if __name__ == '__main__' block. (But the variable c isn't.)

  • You can put whatever you want in the if __name__ == '__main__' in a file if you are only going to import it and not run it directly -- for example, you can put testing code which you do now want to run automatically.