Why is it necessary to “import” a library first before usage?

  softwareengineering

My question regards the use of import statements.

In most programming languages I’ve come across (e.g. Python, Scala, Go), it is necessary to first import a library before you can use its functions.

Why do you need to specify this import statement?

Why can’t you just use a function/method, and the environment finds and “imports” the related library/functions automatically?

3

I can think of three main reasons for it:

  • The name of a function or class could be ambiguous. There are dozens of image handling libraries. From which one do I want to use the Image class?

  • In the case there are multiple same named classes that you want to use at the same time, import in python and similar statements in other languages, allow you to alias a classname, so each class can be used with an unambiguous name. You need a statement to do that, so import is used to do it.

  • The library might not be present on the machine. A failing import statement tells you immediately what you need to do to resolve the issue. A run-time failure is much less obvious.

2

What you suggest is possible in some languages like Java and C#: If you use the fully qualified name of the class you want to use, you don’t need to explicitly import anything, the environment will automatically find it.

But you do need to use fully qualified names like new System.Web.MailMessage(). This is a hassle (especially with deeper namespaces). By importing the namespace, you can use the unqualified name like just new MailMessage().

So why isn’t all namespaces imported by default then? Because of name collisions. For example there is both a System.Net.MailMessage and a System.Web.MailMessage. You have to specify explicitly which namespace to import to avoid ambiguity.

Of course library developers could avoid reusing the same name (and it is generally good practice to avoid). But when you have multiple independently developed 3rd party libraries, there is no way to avoid this universally. So this is solved by namespacing and imports.

I don’t know Scala, but I suspects it works the same was as Java.

Python is quite different due to its dynamic nature. The Python import statement actually executes the top-level code in the library file. This code defines the functions and classes in the library. So without the import statement, the types would simply not exist, so there would be no way for the language to find them.

1

LEAVE A COMMENT