__name__ == __main__ trick


This trick is very use full for testing modules which will be written by you.
You can call it as module testing.
Eg. There is a module by name module.py
code shown as below, This module adds two numbers and returns SUM.

1) How actually we use module in application ?
2) How we test module ?
3) How we test application ?

You will get answers for these questions
                                       
            Module.py
  1 #!/usr/bin/python
  2
  3 """
  4 This is module example
  5 file name : module.py
  6 """
  7
  8 print "Debug : __name__ = ",__name__
  9
 10 def add(x,y):
 11     print "Adding numbers"
 12     return x+y
 13
 14 if __name__ == "__main__":
 15     print "Entry point"
 16     print "Sum = ",add(12,8)
 17     print "Exit point"
                                    
            app.py

  1 #~/usr/bin/python

  2 """
  3 This is addition application
  4 Which uses module 'module'
  5 Which contains 'add' API.
  6 """
  7
  8 import module
  9
 10 print "sum = ",module.add(11,44)
                                    
Answer for Question 1
To use module in application all you need to do is import module shown below
Line 8 import module

Answer for Question 2

How to test module to which you are going to import in your application

All you need to do is insert module testing code after line
14 if __name__ == "__main__":

what is this __name__ ??  

__name__ is attribute, value will be "__main__" when code is run as standalone, ie when module itself is executed.

if module is executed by any other application by importing it its value will be
Module name itself.

How do we test application ?

Simple just run application :)

When you execute Module.py (standalone) 

output will be

Debug : __name__ =  __main__

Entry point
Sum =  Adding numbers
20
Exit point

When you execute Application

Debug : __name__ = module
sum =  Adding numbers 55