Python Forum

Full Version: Why do we use __main__ when we can call a function directly?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Everyone,

I am a newbie to Python. As I was learning Functions, I am not able to understand the difference between calling the function directly and calling it under __main__. Is there any advantage to call a function under main? Is it something important like main function in Java?
SomeFn() also gets executed directly and funct() also get executed directly.

My sample code:
def funct():
    print("Value of __name__ is: ", __name__)
    print('This statement is in main function')

def someFn():
    print ('This function is not called under the main function')
someFn()

if __name__ == "__main__":
    funct()
Say for e.g., I have 4 functions fn1, fn2, fn3, fn4 - Will there be any difference if I call them by sequence under main or outside main?
People use __name__ to determine if the script is being imported or not. If it's equal to "__main__" then it's not an import. The idea being, you want to run your main method if and only if you're not being imported.

Java knows to call your main method. Python has no such similarity. When you run or import a script, the contents are executed. So it's up to the script to determine whether it should run its main function or not, rather than being built into the language.
just to add to micseydel's answer. Given your sample code
if you execute your script it will execute both functions (because of line 7 and line 9-10)
if you import it in another script it will execute someFn (because of line7) but will not execute the other one
Thanks to both for the quick response.

Does this mean that if I am not planning to import, then I can just directly call the functions and not put them under main. Apologies for my ignorance, but since I am not able to see the difference or understand which is better of the two, I am asking it again.
yes, you can just call them.
As to which is better - in my opinion it's better to get the habit of using if __name__ =='__main__':
Thanks a ton.. Now it is clear..