Posts

Showing posts with the label Python(namespaces)

What does if __name__ == "__main__": do in Python?

Image
  Whenever a Python interpreter see a python source file, it does two things: 1. set a few special variables including '__name__' in this case 2. execute all the code found in the source file Let me be specific, if write a python source file, you can run it as the main program and also you can import it as a module just like what you do with python standard libraries. So this is where " if __name__ == "__main__": " kicks in.  For intance, # this is the code of foo.py print("foo.py") def foo():     print("Helo, this is the function foo.py!") if __name__ == "__main__":     foo() print("end of the file foo.py") # after execution of file foo.py foo.py Helo, this is the function foo.py! end of the file foo.py If run this foo.py file as the main program, like python foo.py, python interpreter will follow the two steps above: 1. it sets the special variable __name__ to '__main__' 2. it executes all the code in the foo...