Skip to content

numpy/printoptions-restore

Pack Severity Fix Versions
NumPy info unsafe, with xpd check --fix --unsafe-fixes All versions

Restoring print options by hand leaves them changed when an error is raised. Use with np.printoptions(...), which restores them in every case.

saved = np.get_printoptions()
np.set_printoptions(precision=3)
print(table)
np.set_printoptions(**saved)
with np.printoptions(precision=3):
print(table)

The rule reports np.set_printoptions(**saved), which restores options that the code changed earlier. The docs ask for np.printoptions as a context manager, which also restores the options when an error is raised.

With --unsafe-fixes, xpd uses with np.printoptions(...) when the only intervening statement stores a repr() result.

This restores the previous print options. Use $NP.printoptions(...) as a context manager so an exception also restores them.

See all rules in the NumPy pack.