Why import statements are not allowed in function bodies (or any block of code)?

David Wilson dw at botanicus.net
Fri Feb 1 04:52:26 PST 2008


On 1/28/08, Leandro Lucarella <llucax at gmail.com> wrote:
> Is there any good reason for not allowing import statements in function
> bodies or any code block? I think it would be really useful for avoid
> namespace polution, specially in unittests (it's really ugly to import
> things a module will never use except for unittesting).

When I started using D I thought this was pretty ugly too, but in
retrospect I can't see any problem at all any more. Specifically,
importing a module merely brings its symbols into view, it does *not*
result in some magical linking of code from that module or anything
else. In other words, I no longer see any reason why I'd *want* to
import from within a unittest{} block, other than for locality and
perhaps a slight increase in self descriptiveness.

The namespace pollution argument is not compelling: you are going to
run into symbol name conflicts when running your unit tests,
regardless of the import being inside the block or not. This is the
only thing I can see wrong with "pollution". The other "problem",
accidentally using a function you probably desired anyway from inside
real code, just saves a little typing. And since you are writing unit
tests you would have probably caught the other case of using the wrong
function.. :)

I'd love to hear from more experienced D'ers about problems I haven't
considered, but since I am yet to see any kind of name conflict in my
code (4 months on), I'm not really interested in the pollution
argument. It's a corner case (IMHO) not worthy of the syntax change.


David.

---

import std.stdio;

// For unit tests.
import std.foo.bar;
import bar.baz.util;






>
> --
> Leandro Lucarella (luca) | Blog colectivo: http://www.mazziblog.com.ar/blog/
> ----------------------------------------------------------------------------
> GPG Key: 5F5A8D05 (F8CD F9A7 BF00 5431 4145  104C 949E BFB6 5F5A 8D05)
> ----------------------------------------------------------------------------
> Long you live and high you fly
> And smiles you'll give and tears you'll cry
> And all you touch and all you see
> Is all your life will ever be.
>



More information about the Digitalmars-d mailing list