Skip to content

ctypes Stucture._fields_ cannot be set when Structure has been subclassed #100980

Description

@ionite34

Bug report

Currently the method for defining Structure fields that cannot be defined within the class, is to define the class with pass and then set _fields_ outside. But ctypes.Structure incorrectly raises AttributeError, even when no class has ever set a _fields_.

from ctypes import *

class PyObject(Structure):
    pass

class PyVarObject(PyObject):
    pass

class PyTypeObject(PyVarObject):
    pass

PyObject._fields_ = [
    ("ob_refcnt", c_long),
    ("ob_type", POINTER(PyTypeObject)),
]
    PyObject._fields_ = [
    ^^^^^^^^^^^^^^^^^
AttributeError: _fields_ is final

Strangely, suppressing this Attribute error reveals the _fields_ attribute does actually get set?

with suppress(AttributeError):
    PyObject._fields_ = [
        ("ob_refcnt", c_long),
        ("ob_type", POINTER(PyTypeObject)),
    ]

print(PyObject._fields_)
>> [('ob_refcnt', <class 'ctypes.c_long'>), ('ob_type', <class '__main__.LP_PyTypeObject'>)]

Your environment

  • CPython versions tested on: 3.11.1, main
  • Operating system and architecture: macOS ARM, ubuntu x64

Linked PRs

Activity

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

Metadata

Metadata

Assignees

Labels

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions