Skip to content

numpy/printoptions-restore

Rule printoptions-restore
Pack NumPy
Severity info
Fix none, edit by hand
Library versions every version

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.

xpd has no automatic fix. Because the code between the two calls has to move into the with block. Make the change by hand.

xpd prints this message with the issue. A name that starts with $ stands for code from your file.

This restores print options that were changed for a while, and NumPy's docs say to use the context manager for that. Wrap the code in with $NP.printoptions(...) instead, which also restores the options when an error is raised.

Browse the other rules of the NumPy pack.