Send Close Add comments: (status displays here)
Got it!  This site "www.robinsnyder.com" uses cookies. You consent to this by clicking on "Got it!" or by continuing to use this website.  Note: This appears on each machine/browser from which this site is accessed.
Python: __main__
by RS  admin@robinsnyder.com : 1024 x 640


1. Python: __main__
A Python program and/or module is easy to create and has a simple form. Just add the code.

I typically use the program and module form of the following, for, say, a main file and a module file. Actually, I use a formatter system so main2.py gets formatted to rmsMain.py (and possibly other files), which is how I got started with this model.

2. Another model
Another model is to use the __main__ built-in variable. Many programmers like this model as it allows the concept of a module to be combined with test and/or other code - but only if the Python program/script is the top-level script. This is detected via the __main__ built-in variable.

3. Main script
Note that a Python program/script called __main__.py as part of a package would be executed if the module is run with the -m parameter.

4. Script without __main__
Here is the Python script without __main__.

Here is the Python code [#1]

Here is the output of the Python code.


5. Script with __main__
Here is the Python script with __main__.

Here is the Python code [#2]

Here is the output of the Python code.


6. Comparison
The Python script without __main__ is cleaner, especially for beginning students.

The Python script with __main__ facilitates unit testing and reduces the number of file as projects grow larger.

The Python script with __main__ also helps make Python scripts model more closely (if that is important) languages such as C, C++, Java, C#, etc. where there needs to be a main function.

7. End of page

by RS  admin@robinsnyder.com : 1024 x 640