importlib
importlib is the standard library module that lets you import modules by a name held in a string and read information about installed packages.
Used in 108 lessons of the course, from 00.02.
import is the normal way to bring in a module. importlib is the machinery behind that statement, exposed as code you can call.
Two uses are the most common:
importlib.import_module("json")imports a module from a string. Use it when the name is decided while the program runs.importlib.metadatareads data about installed packages, such as their version.
In the course you will see from importlib import metadata, mostly from lesson 00.02 on. It is used to ask which version of a package you have installed. The reason is that the real version comes from your environment, not from what you think you installed.
from importlib import metadata
print(metadata.version("pip"))
If the package is not installed, Python raises PackageNotFoundError.
Reach for it when: you need to import a module whose name is in a string, or when you want to know which version of a package is installed.
Examples
Common mistake
import importlib
mod = importlib.import_module("modulo_que_no_existe")Why: The string does not match any module Python can find. `import_module` fails just as `import` would.
How to write it: Check the name and that the package is installed, or catch the error with try / except ModuleNotFoundError.
Common mistake
from importlib import metadata
print(metadata.version("paquete-que-no-existe"))Why: `metadata.version` looks for an installed distribution with that name and does not find it.
How to write it: Use the name the package is installed under (the pip name) and catch metadata.PackageNotFoundError if it may be missing.
