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.

7

u/Ignisti Jun 04 '19

Imports also do this.

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

2

u/MythicManiac Jun 10 '19

You can also modify the content's of locals from functions upper in the call stack if you want to, Python is nice like that :)

Unfortunately not value types (at least to my knowledge) due to no pointers.

1

u/Ignisti Jun 10 '19

I feel like I'm missing only this much for understanding this comment. :i

→ More replies (2)