Search code examples
pythonnumpydoctestnumpy-2.x

How to stop numpy floats being displayed as "np.float64"?


I have a large library with many doctests. All doctests pass on my computer. When I push changes to GitHub, GitHub Actions runs the same tests in Python 3.8, 3.9, 3.10 and 3.11. All tests run correctly on on Python 3.8; however, on Python 3.9, 3.10 and 3.11, I get many errors of the following type:

Expected:
    [13.0, 12.0, 7.0]
Got:
    [np.float64(13.0), np.float64(12.0), np.float64(7.0)]

I.e., the results are correct, but for some reason, they are displayed inside "np.float64".

In my code, I do not use np.float64 at all, so I do not know why this happens. Also, as the tests pass on my computer, I do not know how to debug the error, and it is hard to produce a minimal working example. Is there a way I can make the doctests pass again, without changing each individual test?


Solution

  • This is due to a change in how scalars are printed in numpy 2:

    numpy 1.x.x:

    >>> repr(np.array([1.0])[0])
    '1.0'
    

    numpy 2.x.x:

    >>> repr(np.array([1.0])[0])
    'np.float64(1.0)'
    

    You should restrict the version of numpy to be 1.x.x in your requirements file to make sure you don't end up installing numpy 2.x.x:

    numpy ~> 1.26
    

    (same as numpy >= 1.26, == 1.*, see this answer)

    or update your code to work with numpy 2 and change it to numpy ~> 2.0.