Skip to content

Commit 6cf50eb

Browse files
committed
Add pytest option --warn-numpy-data-promotion
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>.
1 parent 312b0c2 commit 6cf50eb

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

conftest.py

+12
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
# limitations under the License.
1414

1515
import pytest
16+
import numpy as np
1617

1718

1819
def pytest_addoption(parser):
@@ -25,6 +26,12 @@ def pytest_addoption(parser):
2526
parser.addoption(
2627
"--enable-slow-tests", action="store_true", default=False, help="run slow tests"
2728
)
29+
parser.addoption(
30+
"--warn-numpy-data-promotion",
31+
action="store_true",
32+
default=False,
33+
help="enable NumPy 2 data type promotion warnings"
34+
)
2835

2936

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

58+
# If requested, globally enable verbose NumPy 2 warnings about data type
59+
# promotion. See https://numpy.org/doc/2.0/numpy_2_0_migration_guide.html.
60+
if config.option.warn_numpy_data_promotion:
61+
np._set_promotion_state("weak_and_warn")
62+
5163
for item in items:
5264
for k in skip_keywords.intersection(item.keywords):
5365
item.add_marker(skip_marks[k])

0 commit comments

Comments
 (0)