Python for Programmers: Importing and the Standard Library
Welcome to the Importing and the Standard Library lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
We've seen built-in functions like
lenand built-in data types likedict. These are always available globally. Python also has a rich standard library, which is a set of modules providing functionality beyond core language features.For example, the standard library has a
mathmodule that exports asqrt(square root) function. We canimport mathto get access to the module, then callmath.sqrt.>
import mathmath.sqrt(25.0)Result:
5.0
Modules can export any value, not just functions. For example,
mathexports the constantpi.>
import mathmath.piResult:
mathalso exports aceilfunction (ceiling), which rounds a number up to the closest integer.>
import mathmath.ceil(math.pi)Result:
4
Sometimes we use an imported function many times. To keep those calls short, we might want to call
ceil(...)instead ofmath.ceil(...). If we only imported asimport math, then accessingceilis aNameError. (You can typeerrorwhen a code example will cause an error.)>
import mathsqrt(25.0)Result:
NameError: name 'sqrt' is not defined
We could assign the function to a name, then call it that way.
>
import mathsqrt = math.sqrtsqrt(25.0)Result:
5.0
However, it's better to use a "qualified import", like
from math import sqrt. Each imported name is available in the namespace, without requiring themath.prefix.>
from math import sqrtsqrt(25.0)Result:
5.0
Qualified imports can import multiple names at once. We separate them with commas, like
from some_module import name_1, name_2.>
from math import ceil, piceil(pi)Result:
4
We can use
asto use a different name for our imports. It works on imported modules and on qualified imports.>
import math as mm.sqrt(25.0)Result:
5.0
>
from math import ceil as ceiling, pi as PIceiling(PI)Result:
4
This can be useful to avoid naming conflicts, or to give imports shorter names.
For example,
pandasis a common data science library in Python. Instead of qualified imports, most pandas code starts withimport pandas as pd. That lets us refer to the functions quickly, likepd.read_csv. Thepd.makes it clear that they came from pandas.