Skip to content

With NumPy 2.0, text/plain + float formatting results in SphinxWarning #610

@bryanwweber

Description

@bryanwweber

Describe the bug

context
When I do glue a NumPy float into a page with the {glue:text}`variable:<float format>`, I get a SphinxWarning:

sphinx.errors.SphinxWarning: <filename>:257:Failed to format text/plain data: could not convert string to float: 'np.float64(0.9643970836113095)' [mystnb.glue]

expectation
I expected no warning to occur.

problem
This is a problem for people doing formatting floating point NumPy objects because if they turn warnings to errors, their pages won't build.

The cause is described here: https://numpy.org/devdocs/release/2.0.0-notes.html#representation-of-numpy-scalars-changed

Basically, the repr of NumPy types changed to include the NumPy type. As such, the IPython display formatter outputs the literal 'numpy.float64(1.2345)' which obviously can't be formatted as a float. I'm not sure if this should be filed here or with IPython... I landed on here because it affects the glue functionality in particular and because it seems like the display formatter for NumPy types in IPython is probably doing the right thing.

The immediate workaround is as suggested in the NumPy release notes, setting np.set_printoptions(legacy="1.25") fixes the warning.

Reproduce the bug

  1. Install NumPy 2.0
  2. Glue and print a variable:
    ```{code-cell}
    from myst_nb import glue
    import numpy as np
    a = np.float64(1.234)
    glue("var-a", a)
    ```
    {glue:text}:`var-a:.2F`
  3. Build a book/the page and see the warning/error if -W is on.

List your environment

❯ jupyter-book --version
Jupyter Book      : 1.0.0
External ToC      : 1.0.1
MyST-Parser       : 2.0.0
MyST-NB           : 1.1.0
Sphinx Book Theme : 1.1.3
Jupyter-Cache     : 1.0.0
NbClient          : 0.10.0

and most importantly, NumPy >=2.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions