Tuesday, January 13, 2009

PEP 8 is prescriptive about the preferred location for import statements:
Imports are always put at the top of the file, just after any module
comments and docstrings, and before module globals and constants.
This has bugged me. I think it reminds me of the "include the world" messes I saw in C++ code that resulted in massive overdependency and lengthy recompilations. With the import remote from the use, it is easy for crud to accumulate. Someone writes a tiny method (for debugging, as an experiment, for a one-off) that uses something used nowhere else in the module and now everything in the module is (lexically) dependent on that import, and so is the module's every consumer. Ugh.

I wonder what the rationale is. A benefit is that missing modules will be discovered early: "cannot import" complaints will appear at startup, not after a possibly lengthy time of apparent stability when a rare event occurs. A drawback is that some refactoring, e.g. moving a class to its own module, is tricky to do perfectly. If I copy the entire import block to the new module, it is guaranteed to work, but there is a good probability that that block will be more than necessary, because the module was a candidate for refactoring in the first place.

So I prefer import statements to go in the class; and the basis of this preference is that I think of the class as the unit of reuse, not the module; and I think that because I am still speaking Python with a C++ accent.