On Oct 6, 3:56 pm, Steven D'Aprano <ste...@remove.this.cybersource.com.au> wrote: > On Tue, 06 Oct 2009 18:42:16 +0200, Diez B. Roggisch wrote: > > The most common problem is that a file is used as module and as > > executable at the same time. > > > Like this: > > > --- test.py --- > > > class Foo(object): > > pass > > > if __name__ == "__main__": > > import test > > assert Foo is test.Foo > > > --- > > > This will fail when executed from the commandline because the module is > > known twice - once as "__main__", once as "test". > > Why would a module need to import itself? Surely that's a very rare > occurrence -- I think I've used it twice, in 12 years or so. I don't see > why you need to disparage the idea of combining modules and scripts in > the one file because of one subtle gotcha.
I'm sorry, this can't reasonably be characterized as a "subtle gotcha". I totally disagree, it's not a gotcha but a major time- killing head-scratcher, and it's too thoroughly convoluted to be called subtle (subtle is like one tricky detail that messes up an otherwise clean design, whereas this is like a dozen tricky details the mess the whole thing up). It's easily the most confusing thing commonly encountered in Python. I've seen experts struggle to grasp the details. Newbies and intermediate programmers should be advised never to do it, use a file as either a script or a module, not both. Expert programmers who understand the issues--and lots of experts don't--can feel free to venture into those waters warily. I would say that's an inferior solution than the method I advised in another thread that uses a single script as an entry point and inputs modules. But I'm not going to tell an expert how to do it. Average programmers, yes I will. Too easy to mess up, too hard to understand, and too little benefit, so don't do it. File should be either a module or script, not both. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list