Python 101 : The " __name__ = 'main()' " expression


Sometimes, for some reasons, we may want our code to run from the main program, not from imported code using the "import" syntax.

Before running a program python gives the internal "__name__" variable the name of the program it is running from or the value "__main__" if python runs the program directly and not from imported code.

Remark:

The "import test" for example - in the below example - imports and runs the code from "test.py" and not directly.

Below is a simple example:



And from another program "test1.py":


We can check if the code is directly run by python or imported using the below:

Comments

Leave as a comment:

Archive