Search code examples
pythonif-statementmethodsprogram-entry-point

Python main method options


let's assume that I have two python scripts. One of them is like:

def sum(x,y):
   return x+y 

def main():
  sum()

if __name__ = '__main__':
    main()

The other ones:

def sum(x+y):
    return x+y

  if __name__ == '__main__'':
       sum()

What is the difference between two option? Or is there any difference between write main method and then if statement and writing just if statement? If you explain it, I will be grateful. Thank you so much for your answers and time.


Solution

  • Second case has a syntax error, so assuming that you meant to do:

    def sum(x, y):
        return x+y
    

    Both cases will yield the same result however, you'll find that often, a function named main() encapsulates the program’s primary behavior, so it's something most programmers expect to see. However there's nothing special about naming a function 'main()' or something else like 'primary_func()' the behavior will be the same.

    However, there is 'something' special about naming a function 'sum()', the name 'sum' is a 'Built-In Namespace'. In general, it is considered bad practice to name functions using 'Built-In Namespaces'. These are reserved keywords/names that Python makes available for specific purposes. Some examples of 'Built-In Namespaces' include: max, int, print, sum, and name.

    You can use the following statement to list all the Built-In Namespaces:

    print(dir(__builtins__))
    

    You'll note that 'main' is not a Built-In Namespaces and therefore is safe to use.