@Cryoris answer is perfectly valid, but a more "Pythonic" way of doing this is with the help of the with
keyword:
import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=DeprecationWarning)
# Run VQE here, respect the identation.
# /!\ At this level of identation, warnings are no longer ignored.
# No need to think to call another method afterwards.
The issue with this code being that you ignore all the deprecation warnings. If you want to only ignore the one that bother you, add a filter:
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore",
category=DeprecationWarning,
message=(
"The Python built-in round is deprecated for complex "
"scalars, and will raise a TypeError in a future release. "
"Use np.round or scalar.round instead."
)
)
# Run VQE here, respect the identation.
# /!\ At this level of identation, warnings are no longer ignored.
# No need to think to call another method afterwards.
This answer has been constructed from this other answer and the warnings
module documentation.
I tested with
import warnings
def f():
warnings.warn("The Python built-in round is deprecated for complex scalars, and will raise a TypeError in a future release. Use np.round or scalar.round instead.", DeprecationWarning)
with warnings.catch_warnings():
warnings.filterwarnings("ignore",
category=DeprecationWarning,
message=(
"The Python built-in round is deprecated for complex "
"scalars, and will raise a TypeError in a future release. "
"Use np.round or scalar.round instead."
)
)
print("In 'with' block:")
f()
print("Done")
print("Out of 'with' block:")
f()
print("Done")
that prints
In 'with' block:
Done
Out of 'with' block:
-c:2: DeprecationWarning: The Python built-in round is deprecated for complex scalars, and will raise a TypeError in a future release. Use np.round or scalar.round instead.
Done
in my IPython session. You can check that the warning has been filtered within the with
block and not filtered outside of it.