Python Main Function & Method Example: Understanding __main__

Posted in /  

Python Main Function & Method Example: Understanding __main__
vinaykhatri

Vinay Khatri
Last updated on April 25, 2024

    If you are familiar with programming languages like C++ and Java then you must know about the main() function. Upon code compilation, it executes first before any other code statement. But in Python, the code executes line-by-line, from top to bottom, so there is no specific main() function. However, there is __name__="__main__" in Python that shows some similarities with the main() function in other programming languages.

    This article will detail a Python main function & method example. In this Python tutorial, you will learn what is the __name__ variable in Python, how to use the main() function in Python, and what does __name__ ="__main__" do in Python.

    How to Define the main() Function in Python?

    Although there is no such concept of a main() function in Python, we can write a program that can perform the same functionality. For example:

    #Python code

    def fun1():
        print("Fun1 function")
    
    def main():
        print("Hello world")
        
        #call another function
        fun1()
    
    if __name__=="__main__":
        #explicitly call main() function
        main()

    Output

    Hello world
    Fun1 function

    The above Python code is equivalent to the following C++ code:

    //C++ Code

    #include <iostream>
    using namespace std;
    
    void fun1(){
        cout<<"Fun1 function";
        }
    
    int main()
        {
          cout<<"Hello world"<<endl;
         
         //call another function
         fun1();
         return 0;
        }

    Output

    Hello world
    Fun1 function

    In the above C++ and Python programs, you can see that in Python, we have to call the main() function explicitly. This is because Python does not support the concept of a main() function, and it treats the def main(): function as a user-defined function. On the other hand, in C++ code, we only defined the main() function but did not call it. Despite so, the main() function gets executed and calls the fun1() function. This is because the C++ compiler automatically calls and executes the main() function. But to execute or compile functions other than the main() function, we have to call them as we did with the fun1() function. In the above Python code, also notice the if __name__=="__main__": statement. What does this statement do? We will be covering this topic and Python main function & method example in the next sections of this article, but before that, you need to know what is the __name__ variable in Python.

    What is the __name__ Variable in Python?

    There are various ways to execute a Python script or program. Among all the various ways, the two most common ones are:

    1. Executing a Python script directly.
    2. Using the import statement to execute the Python script indirectly.

    __name__ is an inbuilt variable in Python whose value gets set automatically when the Python program enters execution. Before executing the first line of a Python script, the Python interpreter sets the value of the __name__ variable. When we directly execute a Python script, the inbuilt python variable sets to the string value of __main__ . But if we indirectly execute a Python script using the import statement, then the __name__ variable of the imported Python file sets to the script file name.

    Example

    Let's execute a Python script directly and see what it is the value of the __name__ variable in this case:

    #example1.py

    print("The __name__ variable value of example1.py script is:")
    print(__name__)

    Execute the example1.py (Output)

    The __name__ variable value of example1.py script is:
    __main__

    In the above output, you can see that the value of the __name__ variable for the example1.py file is __main__ , but if we import it in another Python script, its value will change.

    #example2.py

    #this will execute example1.py
    import example1
    
    print("The value of example2.py __name__ is:")
    print(__name__)

    Execute the example2.py (Output)

    The __name__ variable value of example1.py script is:
    example1
    The value of example2.py __name__ is:
    __main__

    Now, you can see that when we import the import example1 Python script in example2.py Python script, the value of __name__ for example1.py changes from __main__ to example1 , and now example2.py __name__ variable has the value of __main__ . This is because the value of the __name__ variable is set to __main__ for that script while we are executing directly, and for all the imported scripts, the value of __name__ becomes the file name. That's why when we execute the example1.py script directly the value of __name__ was __main__ , but when we import it, its value becomes the same as the file name, i.e., example1 .

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

    You have often seen the if  __name__ == "__main__" statement in many Python scripts. So, what does it mean? So far, we only know that the __name__ variable is set to __main__ when the Python script is directly executed. If we use more technical terms, we can say that the __main__ is the name of the Python script if it is executed as the top-level code . The Python if __name__ =="__main__": statement checks if the Python script is executed at the top-level or directly. With the if statement, we can specify a set of code that should only execute if that Python script is executed directly. Let's understand the working of if __name__=="__main__": statement with an example.

    Example

    #example1.py

    if __name__=="__main__":
        print("This print statement is exclusive for example1.py")
    
    print("Example1.py: execute any way")

    Output (example1.py)

    This print statement is exclusive for example1.py
    Example1.py: execute any way

    # example2.py

    import example1
    
    if __name__ =="__main__":
        print("This statement is exclusive for example2")
    
    print("Example 2: print anyway")

    Output(example2.py)

    Example1.py: execute any way
    This statement is exclusive for example2
    Example 2: print anyway

    In the above example, you can see that when we execute the example1.py script, it prints two statements:

    This print statement is exclusive for example1.py
    Example1.py: execute any way

    But when we execute example2.py , it executes only one print() statement from the example1.py file.

    Example1.py: execute any way
    This statement is exclusive for example2
    Example 2: print anyway

    This is because the first print() statement that is inside the if __name__ =="__main__": statement becomes False because the example1.py script is executed indirectly, and the value of __name__ for the example1.py script becomes example1 and not __main__ .

    Conclusion

    That sums up our Python main function & method example. __name__ is the inbuilt variable for every Python script. The value of __name__ gets set automatically when the Python program is executed. If the Python script is executed directly, then the value of the __name__ variable for that script becomes __main__ , but if the script is imported or run indirectly as a module, the __name__ value for that Python script becomes the module name itself. The __name__ =="__main__" statement is generally used with if statement to check if the particular script is executed directly or imported indirectly. And with the if statement the __name__=="__main__" statement can be represented as the main() function for a Python program.

    People are also reading:

    Leave a Comment on this Post

    0 Comments