[Tutor] Which is better Practice and why

Devin Jeanpierre jeanpierreda at gmail.com
Tue Oct 23 03:17:14 CEST 2012

On Mon, Oct 22, 2012 at 8:42 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> If you do that, and the module directly or indirectly imports itself
> while it is running as a script, you may run into trouble. But writing
> a dual-purpose module that is usable as an importable module or as a
> stand-alone script is not problematic in itself.

Yes. However, it is somewhat hard to guarantee that a module won't
indirectly import itself for a large codebase. It certainly sometimes
happens by accident.

>> So use the first one always.
> This is contrary to the advice given in the Fine Manual:
> http://docs.python.org/library/__main__.html
> More from Python's creator, GvR, and the Effbot:
> http://www.artima.com/forums/flat.jsp?forum=106&thread=4829
> http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm

It's very easy for me to overstate my case. Maybe I even have already,
just because I wasn't taking very long to explain myself.

I have concrete reasons to not use this form. It comes up very rarely,
and is not a large issue. Heck, it's not even really worth making a
big fuss over. But there is the occasional mess-up where it happens.

I am also aware that what I prefer goes against idiom. But to me, this
minor concrete use-case beats out idiom. After all, what is the
benefit to following this particular idiom? I believe the answer is,
"you get to use one .py file instead of two" -- and as I see it, the
cases where circular imports might be a problem are precisely those
where you don't care too much about the number of files, because
you're writing a package anyway.

As it happens, I sort of stumbled across this worldview when I was
forced into separating modules from scripts with the new __main__
submodule system to make executable packages (So it's even possible
for Pythonic code to forgo the name check). It really struck something
in me, and I had a (subjective) realization that modules and scripts
are fundamentally different, and that there's very little benefit to
conflating them. I realize this isn't really a view that's mainstream
for Python. Also, I realize it's not a particularly interesting
realization -- any C# programmer would tell you this. And presumably,
Pythonistas as a group would disagree.

(As an aside, I find it interesting how much more beautiful GvR's code
in that post becomes if you consider turning the common bits into a
@main decorator).

-- Devin

More information about the Tutor mailing list