Imports - same directory
In the next few lessons we will learn how we can import both internal and
external libraries. We've already seen how this works in external fashion,
when we imported libraries such as pandas
or yaml
. In those cases we imported external libraries that
others wrote, in this lesson we will cover that aspect, as well as importing
libraries we write ourselves.
The reserved keyword import
in Python indicates that the
following term is a library to be included in the current file. Optionally,
as
can be used to assign an alias, a different name,
to the imported library for convenience. A common example is importing the
NumPy library with an alias, for example: import numpy as np
. Once imported,
the classes and functions from the library can be accessed using dot notation.
For example, in the While loops lesson we used the
random.choice
function to randomly select an element from a list.
Since this function is in the NumPy library we called it with
np.random.choice
.
Assume the first code block is in file array_searcher.py, and the second is in main.py. We want to import the functions from the former to be available to use in the latter. Let's see an example of this.
def penultimate_min(arr):
res = sorted(arr)
return res[1]
def penultimate_max(arr):
res = sorted(arr)
return res[-2]
import array_searcher as arrsearch
if __name__ == "__main__":
arr = [10, 9, 5, 7]
res = arrsearch.penultimate_min(arr)
print(res)
res = arrsearch.penultimate_max(arr)
print(res)
Running the code in main.py
produces:
> 7
> 9
In main.py
, to import the functions in file array_searcher.py
,
we import it with the name of the file, omitting the .py
extension;
it is then aliased as arrsearch
. Functions found within it can then be
called via dot notation.
Additionally, functions or classes can be imported directly, streamlining the code by reducing the text needed to call a function. This approach also limits the exposure of unwanted functions. With direct import, these functions or classes can be used as described previously, but without the need to prefix them with the library name. Let's see an example of this style of import.
from array_searcher import penultimate_min
Practice Question
Q01.a. Given the following files, which will have access to functions found in fileA?
# fileA.py
import fileC
# fileB.py
import fileA
import fileC
# fileC.py
Q01.b. For the same files, which will have access to functions found in fileB?
Q01.c. For the same files, which will have access to functions found in fileC?
score: 0%