Import vs using (v0.7)

I was reading the Pkg documentation for Julia v0.7 and I noticed that the examples use import. I was wondering if this represents idiomatic Julia and if import is recommended over using.

Having clear what using and import do, is it better to consistently use import – thinking that it doesn’t add the modules to be searched, so it provides better performance?

2 Likes

There is no performance difference, the difference is if the exported variables are brought into scope. using is nice for interactive code but for library code it is in my opinion more descriptive (at least when the code size starts to get larger) to use import.

Compare e.g.

using A, B, C # A exports p, B exports y, C exports z

foo(x) = p(x) + y(x) + z(x)

vs

import A, B, C

foo(x) = A.p(x) + B.y(x) + C.z(x)

or

import A.p, B.y, C.z

foo(x) = p(x) + y(x) + z(x)

In both the latter examples, it is easy to see where p, y and z comes from. In the first one you have to either run using A, B, C in the REPL and just see where they are defined, or search through the source code of A, B, and C.

9 Likes

I agree, but unless I want to define new methods, I prefer using A: p etc.

This is my “internal style guide”:

  1. using Foo for interactive development, or (rarely) importing extensive namespaces in packages.
  2. import Foo when I want to keep my namespace clean, use qualified Foo.bar,
  3. using Foo: bar, baz in packages,
  4. import Foo: bar, baz in packages when I define many methods for them (otherwise import Foo, Foo.bar(::Stuff) = ...).
10 Likes

Yes, I also use import only for functions I want to overload.

1 Like

Thank you very much, that’s good to know. Indeed, in library development I prefer fully qualified names – while for user facing APIs I prefer shorter names.

If I don’t need to extend methods I routinely go with using. I was considering changing that to import statements, hoping it would provide a performance gain. It’s good to know that there is none so I won’t bother doing it.

Revisiting this topic, is it possible to combine

import SomePackage
using SomePackage: f

into a single line? Note that AFAIK in v0.7, using per se does not bring the package name into the namespace.

using SomePackage: SomePackage, f

is now deprecated.