Skip to content

ctypes: array slice assignment replaces the value's __len__ exception with a ValueError #161840

Open

Description

@grgalex

Bug report

Summary

Assigning a sequence to a slice of a ctypes array calls PySequence_Length on the value. When the value's __len__ raises, PySequence_Length returns -1 with the exception set, and the code reads the -1 as a length. The comparison -1 != slicelen is always true, so it raises its own ValueError("Can only assign sequence of same size") over the pending exception, which replaces it.

Expected: the exception from __len__ should propagate.

Reproducer

import ctypes

class BadLen:
    def __len__(self):
        raise KeyError("len raised")

arr = (ctypes.c_int * 3)()
arr[0:1] = BadLen()
ValueError: Can only assign sequence of same size

CPython versions tested on:

CPython main branch

Operating systems tested on:

Linux

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions