[Tutor] Which is better Practice and why

eryksun eryksun at gmail.com
Mon Oct 22 17:14:55 CEST 2012

On Mon, Oct 22, 2012 at 9:35 AM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
> It is also sometimes useful to define a number of scripts that are in
> the same directory but share some code by importing one another. You
> need the if __name__ =="__main__" block for this.
> The problem that Devin is referring to only happens in certain odd
> situations where the script that you run ends up importing itself
> (perhaps indirectly). I have never personally had that problem though.

Just to clarify that I'm following you, would you count the following
as a script importing itself 'indirectly'?

Assume two modules in the same directory, mod1.py and mod2.py, can
both act as the main entry point, and both import each other (assume
no circular import problem). Then if mod1.py runs as __main__ and
imports mod2, and mod2.py imports mod1, there are 2 copies of the
classes and functions defined in mod1.py. For example, there's
__main__.MyError vs mod1.MyError.

I agree there's no problem if no other module imports the module
currently running as __main__. In that case, there's nothing
technically wrong with mixing script functionality into a module that
can also be imported. Self-contained test cases are a clear example of

Also, modules can "import __main__", but it's not used frequently. I
count 16 cases of this in the 2.7.3 standard library, for
introspective usage such as in idlelib, cProfile, pdb, etc.

More information about the Tutor mailing list