close
The Wayback Machine - https://web.archive.org/web/20230127120439/https://github.com/python/cpython/issues/100980
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ionite34 opened this issue Jan 12, 2023 · 0 comments
Open
Labels
expert-ctypes type-bug An unexpected behavior, bug, or error

Comments

@ionite34
Copy link
Contributor

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
@ionite34 ionite34 added the type-bug An unexpected behavior, bug, or error label Jan 12, 2023
@ionite34 ionite34 changed the title ctypes._fields_ cannot be set when Structure has been subclassed ctypes Stucture._fields_ cannot be set when Structure has been subclassed Jan 12, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
expert-ctypes type-bug An unexpected behavior, bug, or error
Projects
None yet
Development

No branches or pull requests

2 participants