[Tutor] Which is better Practice and why

Steven D'Aprano steve at pearwood.info
Tue Oct 23 02:54:52 CEST 2012

On 23/10/12 11:25, Devin Jeanpierre wrote:
> On Mon, Oct 22, 2012 at 6:15 PM, Steven D'Aprano<steve at pearwood.info>  wrote:
>> Not that. That unconditionally executes main the first time you access
>> the module, *regardless* of whether it is being run as a script or
>> being imported. That is nearly always the wrong thing to do.
> Recently I've become a fan of executable packages. In __main__.py,
> it's always the right thing to do.

I would disagree there too. I think that unconditionally running main
is the wrong thing to do, except perhaps in the most trivial quick-and-
dirty scripts. But if the script it that trivial, you might not even
bother with a main function at all.

package.__main__.py is designed to be run as a script, and not to be
imported. But that doesn't mean that there's no good purpose for
importing it. If your package is non-trivial, you ought to have tests
for it, including package.__main__. Those tests will probably want to
import the module, not necessarily run it as a script.


More information about the Tutor mailing list