Alias, imports, requires inside or outside the module?

Looking at the code of Elixir and Ecto core I found some files that have import, alias or require directives in multiple places.

I know that those directives are lexically scoped, but I’m afraid I don’t understand the differences between using them outside or inside the module.

What advantages/disadvantages has one form and the other? Is there a preferred way to go? When should I use one or the other?


As you said the key is lexical scoping. Importing outside of the module makes sense only when defining multiple modules in a single file - the import at the file level will affect all the modules - that’s exactly what’s happening in the ecto associations file - this file defines multiple modules, and importing the functions over and over again would be tiring.

In case of the float module, I see no reason for extracting the import at the file level. It might be some historical left-over, or a preference to single out Kernel exclusions.


Just to echo Michał’s reply, if you have a single module, there is no difference whatsoever.