4 ms·
As a Python beginner I found the ubiquitous if __name__ == '__main__' very confusing...
by lordgrenville 5y ago
As a Python beginner I found the ubiquitous if __name__ == '__main__' very confusing...
- Spivak 5y agoYeah, naming things is hard. In retrospect it really should have been something like __modulename__ but that’s also not right because it doesn’t always return the name of the current module. If you run foo.bar.baz as a script you’ll get __main__ which is actually kinda weird when you think about it. But __modulenameormain__ is a bit long to type. Now the Python devs will say that this is perfectly consistent because the names of modules are determined by the __main__ module and how they’re imported and so the idea that the entry point of a script not being __main__ is preposterous but I don’t think that jives with how people actually write Python code and that “the main module” can actually be “mycompany.app.serverboi” and probably should be for the purposes of logging.
- Doxin 5y agoI mean the real trick there is to not use single-file modules. If you make a folder with a __main__.py and __init__.py you can get rid of the if statement. Not entirely obvious.