Always use: if __name__ == '__main__': ... in Python

preview_player
Показать описание
Today we will be looking at if __name__ == '__main__': ... and what it actually does. I mean we've all noticed it, but why should we actually use it? And what happens if we don't?
Рекомендации по теме
Комментарии
Автор

For such a pretty and readable language like python, this must be one of the most ugly and obtuse looking ways I've ever seen to avoid this type of problem.

With a bit of work, the python devs could've made this feature look good.

In its current state, it really does not feel pythonic.

luizestilo
Автор

Still doesn’t quite answer why this is necessary… If you strictly write functions or classes inside modules, this should not be an issue.

remylau
Автор

So, why does Python use this cumbersome way of preventing code from running on import instead of simply having a default function name or even keyword - I don't know, maybe call it `main` - that will get executed, if you run the file on its own?

"if __name__ == '__main__':" vs. "def main:"

Maybe the first one might me more powerful and can also be reused for some weird metaprogramming stuff that nobody expects and then has to debug for 10 hours. But for 99.9% of all usages the second version would be so much nicer.

clumsyjester
Автор

I don't understand a single word of what you say

alaaafaneh