Optional dependencies enable additional functionality. It’s reasonable to notify the user with a targeted message when they try to use such functionality, e.g.
def plot_data(x, y):
try:
import matplotlib.pyplot as plt
except ModuleNotFoundError:
raise ModuleNotFoundError("'plot_data' requires the optional dependency matplotlib") from None
Instead of just doing a local import and letting the user deal with an unspecific error “ModuleNotFoundError: No module named ‘matplotlib’”.
Since optional dependencies are a language feature, would it make sense to provide a helper in the stdlib to ease their handling? This could be e.g. a function such as
def plot_data(x, y):
importlib.utils.require_dependency("matplotlib")
import matplotlib.pyplot as plt
Yes, everybody can write such a helper themselves in a few lines, but maybe it’s useful enough to have a built-in way of doing this?