1.4 Libraries
While many books are now digital and available online, physical libraries are often still present in towns and cities. You can use a library to avoid doing something yourself, namely, buying a book. You can borrow it and read it. If it is a cookbook, you can use the recipes to make food.
A similar idea exists for programming languages and their environments. I can package together reusable data and functions, and then place them in a library. Via download or other sharing, coders can use my library to save themselves time. For example, if I built a library for math, it could contain functions like maximum, minimum, absolute_value, and is_prime. It could also include approximations to special values like π.
Once you have access to a library by installing it on your system, you need to tell your programming environment that you want to take advantage of it. Languages use different terminology for what they call the contents of libraries and how to make them available.
- Python imports modules and packages.
- Go imports packages.
- JavaScript imports bindings from modules.
- Ruby requires gems.
- C and C++ include source header files that correspond to compiled libraries for runtime.
In languages like Python and Java, you can import specific constructs from a package, such as a class, or everything in it. With all these examples, the intent is to allow your environment to have a rich and expandable set of pre-built features that you can use within your code. Some libraries come with the core environment. You can also optionally install third-party libraries. Part III of this book looks at a broad range of frequently used Python libraries.
What happens if you import two libraries and they each have a function with the same name?
If this happens, we have a naming collision and ambiguity. The solution to avoid this is
to embellish the function’s name with something else, such as the library’s name. That way, you
can explicitly say, “use this function from here and that other function from over there.” For
example, math.sin
in Python means “use the sin
function from the
math
module.” This is the concept of a namespace.