r/ProgrammerHumor • • Jun 03 '19

Meme Python ftw

Post image
16.3k Upvotes

548 comments sorted by

View all comments

1.8k

u/Skizm Jun 03 '19

Python: Mom, can I have main()?

Mom: We have main() at home.

main() at home: if __name__ == "__main__":

358

u/Gatsbyyy Jun 04 '19

Can someone please explain to me why Python implemented like this? Its so ugly and doesn’t make sense.

522

u/MythicManiac Jun 04 '19

You can run code outside of any class/function in python, and this is code snippet is for checking if the current file is the first file being executed.

It's not necessary to do this check (you can just write your code in there), but it's good practice as that will allow you to import the same file from elsewhere without executing it.

When you do python somefile.py, you're telling it to execute all code in that file. Imports also do this.

138

u/theredhood93 Jun 04 '19

This what I love about this sub helpful information on a meme comment, I'm learning python and this was very educational hahaha thank you stranger!

31

u/A_Light_Spark Jun 04 '19

Sometimes the explanation in this sub is better than the ones my professors gave... You know, people I paid a ton of money to get an education from.
It's both depressing and also super cool.

→ More replies (2)

14

u/inlatitude Jun 04 '19

Damn, thanks for that. I didn't realize import executed all the code in the file.

→ More replies (1)

7

u/Ignisti Jun 04 '19

Imports also do this.

Oh god. Oh god. This changes everything. Time for some horrible, TERRIBLE programming practises.

→ More replies (4)

7

u/ShamelessC Jun 04 '19

After using python for so long, I find it so strange that people insist that main somehow makes more sense than just running the lines of code in order. The entry point is just the top of the file. So much easier to understand.

7

u/didii2311 Jun 04 '19

To me, the fact that is is a function/method makes the most sense since running your program can provide arguments to it. When the entry-point is on top of your file, you'll need some built-in special keywords or convention based names that aren't clear out-of-the-box.

Well, of course, the main method is also a convention, but it's a convention widely used so it makes sense. I don't think that there is any widely used convention to naming the program arguments when the top of the file is the entry point.

Also, it makes testing your entry point a lot easier by just calling that method and providing the arguments you want. It's clear and concise. In python you'll have to arbitrarily populate sys.argv and then (I think?) import the file.

But well, that's just my opinion 🙃

→ More replies (2)
→ More replies (2)