2014年12月27日 星期六

[Python] __main__ and __name__

A module in python (usually in form of .py) will be executed by Python interpreter, we normally face the following situations when running python code.


  1. Running the .py directly, like python manage.py
  2. Imported from another module, like from admin import manage.py

So how do python know whether the module is directly run as a main program or it is just a part of another module? The special variable __name__ will do the job!


Take a look at this piece of code

if __name__ == '__main__':
    print 'I am run by itself'
else:
    print 'I am imported as module'

So if the .py is being run as a main program, the __name__ will have value __main__ being set, otherwise, the __name__ 's value will become the module name itself. We can therefore deal with different situations depending on the program's executing behaviour.

沒有留言:

張貼留言