Skip to content

Commit

Permalink
Add pytest option --warn-numpy-data-promotion
Browse files Browse the repository at this point in the history
This adds a new option to make NumPy warn about data promotion behavior that has changed in NumPy 2. This new promotion can lead to lower precision results when working with floating-point scalars, and errors or overflows when working with integer scalars. Invoking pytest with `--warn-numpy-data-promotion` will cause warnings warnings to be emitted when dissimilar data types are used in an operation in such a way that NumPy ends up changing the data type of the result value.

Although this new option for Cirq's pytest code is most useful during Cirq's migration to NumPy 2, the flag will likely remain for some time afterwards too, because developers will undoubtely need time to adjust to the new NumPy behavior.

For more information about the NumPy warning enabled by this option, see
<https://numpy.org/doc/2.0/numpy_2_0_migration_guide.html#changes-to-numpy-data-type-promotion>.
  • Loading branch information
mhucka committed Sep 11, 2024
1 parent 312b0c2 commit 6cf50eb
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

import pytest
import numpy as np


def pytest_addoption(parser):
Expand All @@ -25,6 +26,12 @@ def pytest_addoption(parser):
parser.addoption(
"--enable-slow-tests", action="store_true", default=False, help="run slow tests"
)
parser.addoption(
"--warn-numpy-data-promotion",
action="store_true",
default=False,
help="enable NumPy 2 data type promotion warnings"
)


def pytest_collection_modifyitems(config, items):
Expand All @@ -48,6 +55,11 @@ def pytest_collection_modifyitems(config, items):
del skip_marks["slow"] # pragma: no cover
skip_keywords = frozenset(skip_marks.keys())

# If requested, globally enable verbose NumPy 2 warnings about data type
# promotion. See https://numpy.org/doc/2.0/numpy_2_0_migration_guide.html.
if config.option.warn_numpy_data_promotion:
np._set_promotion_state("weak_and_warn")

for item in items:
for k in skip_keywords.intersection(item.keywords):
item.add_marker(skip_marks[k])

0 comments on commit 6cf50eb

Please sign in to comment.