Why does it do this ? if - __name__ == '__main__'

__name__ is a variable automatically set in an executing python program. If you import your module from another program, __name__ will be set to the name of the module. If you run your program directly, __name__ will be set to __main__.

Therefore, if you want some things to happen only if you're running your program from the command line and not when imported (eg. unit tests for a library), you can use the

if __name__ == "__main__":
  # will run only if module directly run
  print "I am being run directly"
else:
  # will run only if module imported
  print "I am being imported"

trick. It's a common Python idiom.


This will be true if this module is being run as a standalone program. That way, something can act either as a module imported by another program, or a standalone program, but only execute the code in the if statement if executed as a program.

Tags:

Python