You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
ctypes Stucture._fields_ cannot be set when Structure has been subclassed #100980
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_.
changed the title [-]ctypes._fields_ cannot be set when Structure has been subclassed[/-][+]ctypes Stucture._fields_ cannot be set when Structure has been subclassed[/+]on Jan 12, 2023
Subclassing a Structure finalizes it, which prevents setting _fields_. That is the intended behaviour: the superclass's fields are “inherited” (included in the subclass), so they must be known rather early, and they can't change when a new subclass is made. (AFAIK we could delay the finalization a bit more, but that would add hard-to-test edge cases, so let's not.)
The docs could be clearer here.
The bug here is that the _fields_ attribute is set despite AttributeError. This should not happen. (However, the setattr is just “cosmetic”: the internals aren't updated, in fact the attribute is never consulted again after finalization.)
It's confusing that it's possible can finalize a class that doesn't have _fields_ set. However, this feature is useful for superclasses that don't add/affect C fields -- like Structure itself.
Activity
[-]ctypes._fields_ cannot be set when Structure has been subclassed[/-][+]ctypes Stucture._fields_ cannot be set when Structure has been subclassed[/+]TMP: pythongh-100980: Don't set _fields_ if update_stginfo fails
encukou commentedon Sep 20, 2024
Subclassing a Structure finalizes it, which prevents setting
_fields_. That is the intended behaviour: the superclass's fields are “inherited” (included in the subclass), so they must be known rather early, and they can't change when a new subclass is made. (AFAIK we could delay the finalization a bit more, but that would add hard-to-test edge cases, so let's not.)The docs could be clearer here.
The bug here is that the
_fields_attribute is set despiteAttributeError. This should not happen. (However, the setattr is just “cosmetic”: the internals aren't updated, in fact the attribute is never consulted again after finalization.)It's confusing that it's possible can finalize a class that doesn't have
_fields_set. However, this feature is useful for superclasses that don't add/affect C fields -- likeStructureitself.TMP: pythongh-100980: Don't set _fields_ if update_stginfo fails
gh-100980: ctypes: Test, document, and fix finalizing _fields_ (GH-12…