Skip to content

Commit

Permalink
Change how numpy behaves as an optional import (#268)
Browse files Browse the repository at this point in the history
- [x] Closes #267
- [x] Executed `pre-commit run --all-files` with no errors
- [x] The change is fully covered by automated unit tests
- [x] Documented in docs/ as appropriate
- [x] Added an entry to the CHANGES file
  • Loading branch information
jagerber48 authored Nov 15, 2024
1 parent c3da2a4 commit 969324d
Show file tree
Hide file tree
Showing 3 changed files with 203 additions and 130 deletions.
9 changes: 9 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@ Change Log
Unreleased
----------

Changes

- Changed how `numpy` is handled as an optional dependency. Previously,
importing a `numpy`-dependent function, like `correlated_values`,
without `numpy` installed would result in an `ImportError` at import
time. Now such a function can be imported but if the user attempts to
execute it, a `NotImplementedError` is raised indicating that the
function can't be used because `numpy` couldn't be imported.

Fixes:

- fix `readthedocs` configuration so that the build passes (#254)
Expand Down
54 changes: 53 additions & 1 deletion tests/test_uncertainties.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,16 @@
import math
import random # noqa

import pytest

import uncertainties.core as uncert_core
from uncertainties.core import ufloat, AffineScalarFunc, ufloat_fromstr
from uncertainties import umath
from uncertainties import (
umath,
correlated_values,
correlated_values_norm,
correlation_matrix,
)
from helpers import (
power_special_cases,
power_all_cases,
Expand All @@ -15,6 +22,12 @@
)


try:
import numpy as np
except ImportError:
np = None


def test_value_construction():
"""
Tests the various means of constructing a constant number with
Expand Down Expand Up @@ -1313,3 +1326,42 @@ def test_correlated_values_correlation_mat():
numpy.array(cov_mat),
numpy.array(uncert_core.covariance_matrix([x2, y2, z2])),
)


@pytest.mark.skipif(
np is not None,
reason="This test is only run when numpy is not installed.",
)
def test_no_numpy():
nom_values = [1, 2, 3]
std_devs = [0.1, 0.2, 0.3]
cov = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
]

with pytest.raises(
NotImplementedError,
match="not able to import numpy",
):
_ = correlated_values(nom_values, cov)

with pytest.raises(
NotImplementedError,
match="not able to import numpy",
):
_ = correlated_values_norm(
list(zip(nom_values, std_devs)),
cov,
)

x = ufloat(1, 0.1)
y = ufloat(2, 0.2)
z = ufloat(3, 0.3)

with pytest.raises(
NotImplementedError,
match="not able to import numpy",
):
_ = correlation_matrix([x, y, z])
Loading

0 comments on commit 969324d

Please sign in to comment.