On Wed, Jun 07, 2017 at 01:17:39PM +0000, Nicholas Wilson via Digitalmars-d-learn wrote: > On Wednesday, 7 June 2017 at 12:39:07 UTC, Russel Winder wrote: > > Are there any idiom rules as to where to put import statements in D? > > > > In Python they can go anywhere but PEP-8 suggests they should all go > > at the top of a file, just after the module documentation string. > > Well for ones that aren't scoped (i.e. used pervasively throughout the > module) I always put them after the module declaration (if not the > file containing main) and doc comment. > > For scoped imports they go either on the line after the opening brace > of the enclosing scope, or the line before the (selectively) imported > symbol is used (if there is a reasonable amount of code preceding the > opening brace). [...]
I follow the same convention. Though lately, I've been finding myself moving away more and more from global imports, and moving imports into the scope in which they're actually used. While that sometimes necessitates more typing, I find that it also improves code readability and movability: having scoped imports in the block in which the symbol is used means reducing the likelihood of overload conflicts with unfortunately-named symbols (there are a few of these in Phobos). And I can easily move that code into a different source file and have it Just Work, instead of having to twiddle with the import statements at the top of the file (and inadvertently leave useless imports in the original file where they are no longer needed). Nowadays I generally only use module-level import for things that are truly used pervasively, like std.range.primitives, and std.stdio in the module where main() is defined. I try to avoid importing std.stdio anywhere else, unless that module is directly concerned with I/O, and force myself to structure the code such that such a dependency is not needed in the first place -- e.g., write generic range-based algorithms instead of code sprinkled with calls writeln. I found that this has helped improve my code quality significantly, and my code has become much more reusable. T -- The best compiler is between your ears. -- Michael Abrash