If Main

Python, commandline | 01 October 2018

In many Python code, there is a script at the end that starts with if __name__ == ‘__main__’. What it does is to check whether the code is being run from commandline, and if so, it will do certain things. And if the code is not being run from the commandline, then it won’t do those things.

def main():
    # my code
if __name__ =='__main__':
    main()

For example, I have a script called “dashboard.py” that I run first thing in the morning to pull and plot some of the latest financial data that I am interested in. All I have to do the first time is to type “python dashboard.py” on commandline.

def dashboard():
    # my dashboard code
if __name__ =='__main__':
    main()

But what is the __name__ == ‘__main__’?

For SAS users,at least that double underscore looks familiar. SAS special variables, such as __n__, _type_, have double underscores.

Python has special variables as well.

When the Python interpreter reads a source file, it first defines some special variables such as __builtin__ and __doc__. __name__ == ‘__main__’ is one of them.

The purpose of __name__ == ‘__main__’ is to allow us to check if the scipt is being run directly. The actions following __name__ == ‘__main__’ is to happen only if the script is being run directly.

codelearn_path.py
import os
def print_path():
    ABS_PATH = os.path.abspath(__file__)
    print("\n os.path.abspath(__file__) ", ABS_PATH)

    PARENT_PATH = os.path.dirname(ABS_PATH)
    print("\n os.path.dirname(ABS_PATH) ",PARENT_PATH)

    CHILD_PATH = os.path.basename(ABS_PATH)
    print("\n os.path.basename(ABS_PATH) ",CHILD_PATH)
if __name__ =='__main__':
    print_path()

Now, at the command prompt, I type “python C:\Code_only\learn_path_main.py” as shown below, and will get the output that follows.

(base) C:\>python C:\\Code_only\learn_path_main.py
os.path.abspath(__file__)  C:\\Code_only\learn_path_main.py
os.path.dirname(ABS_PATH)  C:\\Code_only
os.path.basename(ABS_PATH)  learn_path_main.py

Some explanations for the output above. os.path.abspath(file) gives the full absolute path. os.path.dirname() gives the parent folder path. os.path.basename() give the filename itself, i.e. the script name itself.

codelearn_main.py
>>> def run_time():
>>>     print("\nRun time action triggered by if __name__ == '__main__'")
>>> def action_at_import_time():
>>>     print("\nImport time action trigged by calling the function")
>>> action_at_import_time()
>>>
>>> if __name__ == '__main__':
>>>     # execute only if run as a script
>>>     run_time()

Now, open the command prompt, or Anaconda Prompt, type “python learn_main.py”, as shown below, we will get the output as expected. Both the first and the second function ran. The second function ran because the name of the module according to the Python interpreter, is __name__ == ‘__main__’.

python learn_main.py
Import time action trigged by calling the function

Run time action triggered by if __name__ == '__main__'

On the other hand, if a module is not the main program but is imported by another one, then __name__ attribute will be the name of the scirpt, in this case it is “learn_main”, not __main__. Since the __name__ is not __main__, then whatever __main__ does will be ignored.

This neat trick helps us reuse code more flexibly.