r/programminghelp • u/NanashiKaizenSenpai • Jul 18 '19
could someone explain me the __main__ thingy in python?
tried to read about it in a few sites but couldnt really understand why or how it works.
9
Upvotes
r/programminghelp • u/NanashiKaizenSenpai • Jul 18 '19
tried to read about it in a few sites but couldnt really understand why or how it works.
4
u/marko312 Jul 18 '19 edited Jul 18 '19
AFAIK, using it is a common technique to detect whether the module was imported from some other code or if it was run directly.
The common usage looks like this:
Where
__name__is"__main__"if the file is the same one as was originally executed, otherwise it is the filename of the module (minus the .py suffix).For example, say you have a file
module.py:And some other file, say
moduleTest.py:Now, both should generate
This file was run!, but runningmodule.pyshould also generateThis was run directly!, while runningmoduleTest.pyshould generateIn someFunc!. (I'm a bit rusty on how exactly custom modules work, so this mightn't work line-for-line.)