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.
CodePudding user response:
As far as I know, the whole if statement structure is just for practical reasons. With a short script, it will not make much of a difference, but with a long script, it can be really nice to use the first one. The first one might make it easier to pinpoint certain errors.
CodePudding user response:
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.