In the previous lesson, we looked at two ways to import something in Python:
- To import a module as a whole
- To import individual module definitions
In this lesson, we'll learn more about modules, but first, let's review some terminology. When importing an entire module, you can refer to it via a dot. Remember what this looks like: module.name
.
There is also a more formal term — qualified name. Accordingly, importing the entire module from the previous lesson is officially called qualified importing.
In Python, we usually place all import
lines at the beginning of the module code. This set of lines is often called an "import block", although syntactically this block isn't highlighted in any way; they're just regular lines one after another. This grouping improves code readability: it makes it easier for developers to find bugs in the code and deal with them.
How to import the whole content of a module
Let's look at the third option - importing the entire contents of a module. It is what it looks like in the code:
from some_module import *
from another_module import *
We implicitly import all definitions here from some_module
and another_module
. Importing in this way gives you access to dozens of variables, constants, and functions, and you don't have to enter the name of the whole module. This feature distinguishes importing content from importing the entire module — and it can also cause readability problems.
Let's look at an example. Imagine a programmer reading someone else's code with imported content. At some point, they will come across the name of an unfamiliar variable and want to know where it came from. You can't just look closely at the block of imports or do a code search. The names of all imported definitions are behind the *
.
It is why most Python writing guides repeat the same advice — import the whole content as rarely as possible. Nevertheless, these imports occur in real-life code, so it is still important to mention this option.
How to combine import methods
The previous lesson was about importing a module as a whole and via individual definitions. To deepen our knowledge, let's look at another way of combining imports in their entirety and separate definitions within the same module.
Let's look at an example. In the module computation.py
, we define this function and these variables:
# file: computation.py
PI = 3.1415926
E = 2.7182818
def pi_times(x):
return x * PI
And in the main.py
module, we'll use two ways to import from the computation.py
module:
# file: main.py
import computation
from computation import PI, E
from computation import pi_times
print(PI)
print(computation.E)
print(pi_times(2))
print(computation.pi_times(E))
You can see from the examples above that you can:
- Use both import methods simultaneously
- Import individual definitions in several steps
- Gain access via a dot to definitions that have already been imported by name