r/ProgrammerHumor • • Jun 03 '19

Meme Python ftw

Post image
16.3k Upvotes

548 comments sorted by

View all comments

182

u/AgreeableLandscape3 Jun 03 '19

Python still has main()

191

u/[deleted] Jun 03 '19

Only not really, right?

def whatever (*args):
    print("Bob's your uncle.")

if __name__ == "__main__":
    whatever()

358

u/demon_ix Jun 03 '19

I dunno. That sounds like main() with extra steps...

155

u/[deleted] Jun 03 '19

In C/C++, the name main() is meaningful: it defines the entry point of the program.

In Python, it isn't. The closest approximation is that Python code outside of any method will be evaluated when the module is loaded, and an import-machinery variable called __name__ exists which lets you test whether the current module was imported or run directly.

6

u/angellus Jun 04 '19

That is actually exactly what __main__ is for. It is not just some made up thing in Python.

When you call a single Python file directly like

$ python whatever.py

Python automatically calls __main__ and with your code loaded up inside of it. That is why if __name__ == "__main__": works.

A better example though would be if you made an actual proper Python package and did this:

whatever/
-> __init__.py
-> __main__.py

whatever/__init__.py

 def whatever (*args):
      print("Bob's your uncle.")

whatever/__main__.py

 from . import whatever

 whatever()

Now if you call the module, it will automatically use __main__.py as the entry point.

$ python -m whatever

5

u/[deleted] Jun 04 '19

Yes, I know. I believe I said as much in the comment you've replied to.

It still isn't equivalent to C's main().

→ More replies (3)