BUG: `write_array_header_1_0/2_0` writes NumPy scalars into the header, which `read_array_header_*` cannot read

Abierto
#33,206 4 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
3/5
Tiempo estimado
1-2 días
Aptitud para principiantes
65/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
numpy, python
Área
backend

Línea de trabajo

Start by reading numpy/lib/_format_impl.py, especially write_array_header_1_0, write_array_header_2_0, and the header-reading path that uses ast.literal_eval; the issue also cites related issue #28334. Reproduce with NumPy scalar values in the shape tuple, then run the relevant format tests. Done when headers written with those values can be read successfully.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

00 - Bug component: numpy.lib
Describe the issue:

If the header dict passed to write_array_header_1_0 (or write_array_header_2_0) contains NumPy scalars, e.g. shape=(np.int64(3), np.int64(7), np.int64(1)), the header is written with their repr (np.int64(3)). This is not a Python literal, so read_array_header_1_0/2_0 fails in ast.literal_eval with ValueError: malformed node or string.

The documentation of these functions only says that d has "the appropriate entries", so we used NumPy scalars based on the input for other functions of the same module.

Similar to issue #28334, which reported it via open_memmap.

Reproduce the code example:
import io
import numpy as np
from numpy.lib import format as fmt

fp = io.BytesIO()
fmt.write_array_header_1_0(fp, {
    'descr': '<i2',
    'fortran_order': False,
    'shape': (np.int64(3), np.int64(7), np.int64(1)),
})
print(fp.getvalue()[10:]) 

fp.seek(0)
fmt.read_magic(fp)
fmt.read_array_header_1_0(fp)
Error message:
# Example printing
b"\x00\x00{'descr': '<i2', 'fortran_order': False, 'shape': (np.int64(3), np.int64(7), np.int64(1)), }                       \n"

# Error trace
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[12], line 15
     11 print(fp.getvalue()[10:])   # ... 'shape': (np.int64(3), np.int64(7), np.int64(1)), }
     12 
     13 fp.seek(0)
     14 fmt.read_magic(fp)
---> 15 fmt.read_array_header_1_0(fp)

File ~/Documents/codex-simbug/numpy-nightly/lib/python3.12/site-packages/numpy/lib/_format_impl.py:548, in read_array_header_1_0(fp, max_header_size)
    511 @set_module("numpy.lib.format")
    512 def read_array_header_1_0(fp, max_header_size=_MAX_HEADER_SIZE):
    513     """
    514     Read an array header from a filelike object using the 1.0 file format
    515     version.
   (...)    546 
    547     """
--> 548     return _read_array_header(
    549             fp, version=(1, 0), max_header_size=max_header_size)

File ~/Documents/codex-simbug/numpy-nightly/lib/python3.12/site-packages/numpy/lib/_format_impl.py:665, in _read_array_header(fp, version, max_header_size)
    654 # The header is a pretty-printed string representation of a literal
    655 # Python dictionary with trailing newlines padded to an ARRAY_ALIGN byte
    656 # boundary. The keys are strings.
   (...)    662 #
    663 # For performance reasons, we try without _filter_header first though
    664 try:
--> 665     d = ast.literal_eval(header)
    666 except SyntaxError as e:
    667     if version <= (2, 0):

File /usr/lib/python3.12/ast.py:112, in literal_eval(node_or_string)
    110                 return left - right
    111     return _convert_signed_num(node)
--> 112 return _convert(node_or_string)

File /usr/lib/python3.12/ast.py:101, in literal_eval.<locals>._convert(node)
     99     if len(node.keys) != len(node.values):
    100         _raise_malformed_node(node)
--> 101     return dict(zip(map(_convert, node.keys),
    102                     map(_convert, node.values)))
    103 elif isinstance(node, BinOp) and isinstance(node.op, (Add, Sub)):
    104     left = _convert_signed_num(node.left)

File /usr/lib/python3.12/ast.py:90, in literal_eval.<locals>._convert(node)
     88     return node.value
     89 elif isinstance(node, Tuple):
---> 90     return tuple(map(_convert, node.elts))
     91 elif isinstance(node, List):
     92     return list(map(_convert, node.elts))

File /usr/lib/python3.12/ast.py:111, in literal_eval.<locals>._convert(node)
    109         else:
    110             return left - right
--> 111 return _convert_signed_num(node)

File /usr/lib/python3.12/ast.py:85, in literal_eval.<locals>._convert_signed_num(node)
     83     else:
     84         return - operand
---> 85 return _convert_num(node)

File /usr/lib/python3.12/ast.py:76, in literal_eval.<locals>._convert_num(node)
     74 def _convert_num(node):
     75     if not isinstance(node, Constant) or type(node.value) not in (int, float, complex):
---> 76         _raise_malformed_node(node)
     77     return node.value

File /usr/lib/python3.12/ast.py:73, in literal_eval.<locals>._raise_malformed_node(node)
     71 if lno := getattr(node, 'lineno', None):
     72     msg += f' on line {lno}'
---> 73 raise ValueError(msg + f': {node!r}')

ValueError: malformed node or string on line 1: <ast.Call object at 0x7c9fe13867d0>
Python and NumPy Versions:

2.6.0.dev0+git20261031.df9913a
3.12.3 (main, Aug 31 2026, 10:18:26) [GCC 13.3.0]

Runtime Environment:

No response

How does this issue affect you or how did you find it:

This issue was identified by an automated testing tool currently being developed by our research team.
Before reporting it, we reviewed the code, documentation and checked the latest development version of Numpy to confirm it.

Lenguaje dominante
Python
Estrellas
33.5k
Forks
13.1k
Merge medio
1 d 19 h
PR fusionados (30 d)
143

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de numpy/numpy

Todos los issues de numpy/numpy

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.