On Sat, Oct 02, 2021 at 01:15:28AM -0400, Jonathan Crall wrote:
On Sat, Oct 2, 2021, 12:05 AM Chris Angelico <rosuav@gmail.com> wrote:
But it's ONLY necessary when a single Python file is used as both a script and a module. Bear that in mind.
That's effectively every module I write. I don't think that's uncommon or bad practice.
It's not *bad* practice as such, or at least not necessarily, but it does open you to a particular failure mode that can be avoided by keeping your scripts and importable modules separate. Things are fine when the one .py file is used as either an importable module, or as an executable script, but if you ever have a situation where the same .py file gets used as both *simultaneously*, then you break the invariant that each module is a singleton. The most common way that occurs is, by memory (untested): # spam.py import eggs if __name__ == "__main__": do_something() # eggs.py import spam When you import spam, you just have a regular old circular import. But when you run spam as a script, you end up with two copies of the module, one called 'spam' and one called '__main__'. Whether that ends up being a problem or not depends on the circumstances. So many people have a coding standard to always keep the two (importable modules and scripts) as separate files. -- Steve