[Tutor] Which is better Practice and why

Steven D'Aprano steve at pearwood.info
Tue Oct 23 11:59:59 CEST 2012

On 23/10/12 12:53, Devin Jeanpierre wrote:
> On Mon, Oct 22, 2012 at 8:54 PM, Steven D'Aprano<steve at pearwood.info>  wrote:

>> 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.
> I think you will find that it is never the case that __name__ !=
> '__main__' in a file called "__main__.py".

I think you'll find that you're wrong there :)

[steve at ando ~]$ mkdir package
[steve at ando ~]$ touch package/__init__.py
[steve at ando ~]$ echo "print(__name__)" > package/__main__.py
[steve at ando ~]$ python package
[steve at ando ~]$ python -c "import package.__main__"

> If I want to test something, I put it in another file.

Yes. And how do you import the __main__.py module to test it, without
it executing?

> My __main__.py file will generally look something like this:
>      from . import game
>      game.Game().run()

Well, that's probably trivial enough that it requires no testing
other than "does __main__.py exist?".


More information about the Tutor mailing list