Skip to content

missing np.get_string_function (counterpart of np.set_string_function) #11266

@boeddeker

Description

@boeddeker

Is it possible to implement a np.get_string_function as counterpart of np.set_string_function?

I found the code for printing

PyArray_SetStringFunction(PyObject *op, int repr)
{
if (repr) {
/* Dispose of previous callback */
Py_XDECREF(PyArray_ReprFunction);
/* Add a reference to new callback */
Py_XINCREF(op);
/* Remember new callback */
PyArray_ReprFunction = op;
}
else {
/* Dispose of previous callback */
Py_XDECREF(PyArray_StrFunction);
/* Add a reference to new callback */
Py_XINCREF(op);
/* Remember new callback */
PyArray_StrFunction = op;
}
}

and it looks like it is currently impossible to get the PyArray_ReprFunction and PyArray_StrFunction in python.
Since my C skills are limited, maybe someone that is familiar with the numpy source code can implement such a function?

My use case is that I have my own pprint and simply reset the string_function at the end, but the correct way would be to restore the previous one:

def pprint(obj):
    from pprint import pprint
    np.set_string_function(
        lambda a: f"array(shape={a.shape}, dtype={a.dtype})"
    )
    original_pprint(obj)
    np.set_string_function(None)  # Wrong, when the user initially changed the string_function

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions