Function-local imports

bearophile bearophileHUGS at lycos.com
Sun Apr 25 18:28:20 PDT 2010


In some situations I'd like to import names inside a function, as sometimes done in Python:

int foo(int x) {
    import std.math: sqrt;
    return cast(int)(sqrt(cast(real)x) * 2);
}


Keeping the import closer to the scope where the name (here sqrt) is used is useful because it keeps the global namespace of the module cleaner. Global names are better minimized.

Importing global names like this can be problematic because later in the module it can be hard to remember where the bar and baz names come from:

from foo import bar, baz;

To avoid this problem you can use:
static import foo;
so later you have to use:
foo.bar
that is states its origin clearly.

Keeping imports closer to the point where the imported names are used lowers the risk of confusing it with something else, while allowing nonstatic imports.

Imports local in a function can be useful in unit tests too, because the can require modules normally not used (for example std.stdio) by the module. version(unittest){...} can be used for a similar purpose.

One disadvantage of function-local imports is that looking at the header of a module you can't tell all the modules it imports, you have to perform a search in the whole module. But this is true for global-level imports too, that can be scattered in the whole module (but they usually aren't). So function-local imports have to be used with care.

Bye,
bearophile



More information about the Digitalmars-d mailing list