Python Modules

Some functionality in Python comes from built-in libraries called modules.

Import Strategies and Namespaces

When we use a variable or function that has been defined within one of these modules, we must import that functionality, using an import statement.

There are two different ways to import in Python.

First, we can import the entire module. If we do, this loads all the functions defined within, and we’ll access those functions through the module namespace:

# EXAMPLE HYPOTHETICAL PSEUDOCODE
import module_name

module_name.function_name()

Alternatively, we can import only the function(s) we care about. This is slightly more performant, as unused functions are not loaded. If we do, we can invoke the functions directly:

# EXAMPLE HYPOTHETICAL PSEUDOCODE
from module_name import function_name

function_name()

With either approach, we can use an alias to give the module or function(s) a short-hand name. If we do, we’ll access those functions through the short-hand namespace:

# EXAMPLE HYPOTHETICAL PSEUDOCODE
import module_name as m

m.function_name()
# EXAMPLE HYPOTHETICAL PSEUDOCODE
from module_name import function_name as fn

fn()

Survey of Python Modules

Here are some common modules in Python, and more information about how to use each: