Steven D'Aprano 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 surprised to see you missed this. A module doesn't generally import itself, but it's an easy mistake for a circular dependency to develop among modules. modulea imports moduleb, which imports modulea again. This can cause problems in many cases, but two things make it worse. One is if an import isn't at the very beginning of the module, and even worse is when one of the modules involved is the original script. You end up with two instances of the module, including separate copies of the global variables. Lots of subtle bugs this way.

And there have been many threads right here, probably an average of once every two months, where the strange symptoms are ultimately caused by exactly this.

DaveA

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to