In the context of this lesson, we have the option to import the entire module or just specific functions and objects from the module. Should I always import an entire module when using it, or just the specific attributes?
You can absolutely import the entire module or just the specific attributes from the module in your program; the choice can come down to the context of your program and what it requires from a module.
Say that your program only requires the
math.sqrt() function to perform some calculations. In this case, you might consider just importing this single function, like
from math import sqrt # sqrt()
rather than importing the entire math module. One reason for this is to avoid polluting the namespace, so that there aren’t conflicts with objects you define in the local namespace of the program.
One thing to note is that when importing an attribute from a module, like
from math import sqrt, the entire module,
math, will still be fully imported, so there isn’t much, if any, improvement from importing just a specific attribute versus the entire module. As a result, choosing to import either the entire module or a specific attribute from the module can also come down to syntax choices, for example,