0

Although I've been using python for a while, and a common pattern you see is these two statements:

def main():
    # Fancy code here 
if __name__ == "__main__":
    main()

My question is, why wouldn't you use this pattern instead?

if __name__ == "__main__":
    # Fancy code here

Is this just in case you want to import main from another place? Or is there some other reason you might want to do this?

BallzofFury
  • 241
  • 2
  • 9
  • 3
    Because then you can call `module.main()`, making the code reusable. – Martijn Pieters Oct 25 '18 at 13:47
  • All right, that makes sense. Thanks for the reply! – BallzofFury Oct 25 '18 at 13:49
  • Wild speculation: some programmers that do this aren't doing it for any practical reason; they're doing it because all of the non-Python languages they've ever used require a main function, and they would feel weird not using it in Python too. – Kevin Oct 25 '18 at 13:53
  • Possible duplicate of [What does if \_\_name\_\_ == "\_\_main\_\_": do?](https://stackoverflow.com/questions/419163/what-does-if-name-main-do) – Andreas K. Oct 25 '18 at 13:57

2 Answers2

1

A function is reusable, you can call it from other code. Code under the if __name__ guard can't so be invoked.

It makes testing and encapsulation easier. All you need is

import module

module.main()
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks for the fast reply! That does make sense, but when you're just looking at the code it looks a little silly :) – BallzofFury Oct 25 '18 at 13:49
1

Another reason is to avoid populating the global scope with variables.

Consider this example:

def add_em(arg1, arg2):
    return a + b

if __name__ == "__main__":
    a = 2
    b = 4
    print(add_em(a, b))

Here, the add_em() function clearly has a bug: it should return arg1 + arg2, but since the a and b variables belong to the global scope, this bug will likely go undetected until add_em() is called from another context. Running the script gives no error:

$ python myscript.py
6

Using a main() function would likely detect this earlier:

def add_em(arg1, arg2):
    return a + b

def main():
    a = 2
    b = 4
    print(add_em(a, b))

if __name__ == "__main__":
    main()

Now the error is detected right away:

$ python myscript.py
Traceback (most recent call last):
    ...
NameError: name 'a' is not defined
codeape
  • 97,830
  • 24
  • 159
  • 188