Skip to content

ENH: Support new-style custom dtypes in the buffer protocol #23500

Open

Description

@ngoldbaum

Proposed new feature or change:

Currently the buffer protocol is supported only for a limited number of legacy dtypes (see this switch statement).

In principle it could be possible to encode dtype information in the format string and simply export the buffer as a void* buffer, leaving it up to consumers to parse the exported bytes using the format string. Consumers of the format strings (e.g. cython or any other downstream code working with numpy's buffers) would then need to add support for new dtypes, but at least they'd have a path forward.

See the comment from @eric-wieser #4983 (comment) for more details on how this might work. In principle this is complementary to fixing support for datetimes, so we could also close #4983.

See also the discussion about this in the context of legacy custom dtypes: #18442.

It would probably also be worth checking for any prior discussion about this in CPython's discussion channels or any relevant PEPs.

Activity

  1. seberg commented on Apr 27, 2023

    @seberg
    Member

    I saw this this morning and tried a bit. The thing to note is that Python's memoryview doesn't care at all about what is in the format string, so it is OK to put arbitrary stuff inside. Now, I would want a tentative OK from upstream, but I suspect that can be arranged.

    The diff below, simply encodes the dtype as [numpy.dtypes#DateTime64#s] (module, name, *args. Ignore the # a , is probably nicer. It ends up calling a simple protocol: numpy.dtypes.DateTime64._dtype_from_buffer_fmt(*args, byteorder="="). That could be short-circuit. I didn't import the module here, but if there are no security concerns with just importing (we are not calling arbitrary code after all like pickle) we could do that (but we would trust dtype authors to implement things in a way that doesn't call arbitrary code).

    This works, in the sense that np.array(memoryview(datetime_arr)) round-trips. Of course item access fails with:

    NotImplementedError: memoryview: unsupported format [numpy.dtypes#DateTime64#s]
    

    which is just the same as if the format character would be e.

    Proof of concept diff
    diff --git a/numpy/core/_internal.py b/numpy/core/_internal.py
    index c78385880..786ad833e 100644
    --- a/numpy/core/_internal.py
    +++ b/numpy/core/_internal.py
    @@ -655,6 +655,8 @@ def _dtype_from_pep3118(spec):
         return dtype
     
     def __dtype_from_pep3118(stream, is_subdtype):
    +    import numpy.dtypes
    +
         field_spec = dict(
             names=[],
             formats=[],
    @@ -704,7 +706,15 @@ def __dtype_from_pep3118(stream, is_subdtype):
             # Data types
             is_padding = False
     
    -        if stream.consume('T{'):
    +        if stream.consume("["):
    +            identifier = stream.consume_until("]")
    +            module, name, *args = identifier.split("#")
    +            identifier = getattr(sys.modules[module], name)
    +            byteorder = stream.byteorder if stream.byteorder != "@" else "="
    +            value = identifier._dtype_from_buffer_fmt(
    +                    *args, byteorder=byteorder)
    +            align = value.alignment
    +        elif stream.consume('T{'):
                 value, align = __dtype_from_pep3118(
                     stream, is_subdtype=True)
             elif stream.next in type_map_chars:
    diff --git a/numpy/core/src/multiarray/buffer.c b/numpy/core/src/multiarray/buffer.c
    index c9d881e16..efb8dd7f0 100644
    --- a/numpy/core/src/multiarray/buffer.c
    +++ b/numpy/core/src/multiarray/buffer.c
    @@ -393,7 +393,7 @@ _buffer_format_string(PyArray_Descr *descr, _tmp_string_t *str,
             case NPY_CFLOAT:       if (_append_str(str, "Zf") < 0) return -1; break;
             case NPY_CDOUBLE:      if (_append_str(str, "Zd") < 0) return -1; break;
             case NPY_CLONGDOUBLE:  if (_append_str(str, "Zg") < 0) return -1; break;
    -        /* XXX NPY_DATETIME */
    +        case NPY_DATETIME:     if (_append_str(str, "[numpy.dtypes#DateTime64#s]") < 0) return -1; break;
             /* XXX NPY_TIMEDELTA */
             case NPY_OBJECT:       if (_append_char(str, 'O') < 0) return -1; break;
             case NPY_STRING: {
    diff --git a/numpy/dtypes.py b/numpy/dtypes.py
    new file mode 100644
    index 000000000..817f2d395
    --- /dev/null
    +++ b/numpy/dtypes.py
    @@ -0,0 +1,6 @@
    +import numpy as np
    +
    +class DateTime64:
    +    @classmethod
    +    def _dtype_from_buffer_fmt(cls, unit, byteorder="="):
    +        return np.dtype(f"{byteorder}M8[{unit}]")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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