gh-104533: Add a dataclass-like decorator for ctypes structures#153781
Conversation
Documentation build overview
|
Co-authored-by: Bartosz Sławecki <bartosz@ilikepython.com>
| def struct(class_or_none=None, /, *, align=None, layout=None, endian='native', pack=None): | ||
| process_the_struct = functools.partial( | ||
| _process_struct, | ||
| align=align, | ||
| layout=layout, | ||
| endian=endian, | ||
| pack=pack | ||
| ) | ||
|
|
||
| if class_or_none is None: | ||
| def inner(klass): | ||
| return process_the_struct(klass) | ||
|
|
||
| return inner | ||
|
|
||
| return process_the_struct(class_or_none) |
There was a problem hiding this comment.
I meant it like this:
| def struct(class_or_none=None, /, *, align=None, layout=None, endian='native', pack=None): | |
| process_the_struct = functools.partial( | |
| _process_struct, | |
| align=align, | |
| layout=layout, | |
| endian=endian, | |
| pack=pack | |
| ) | |
| if class_or_none is None: | |
| def inner(klass): | |
| return process_the_struct(klass) | |
| return inner | |
| return process_the_struct(class_or_none) | |
| def struct(class_or_none=None, /, *, align=None, layout=None, endian='native', pack=None): | |
| if class_or_none is None: | |
| return functools.partial( | |
| struct, | |
| align=align, | |
| layout=layout, | |
| endian=endian, | |
| pack=pack, | |
| ) | |
| return _process_struct( | |
| class_or_none, | |
| align=align, | |
| layout=layout, | |
| endian=endian, | |
| pack=pack, | |
| ) |
That's how decorators of this fashion are usually made.
Feel free to ignore.
There was a problem hiding this comment.
process_the_struct isn't defined here; what are you trying to show?
| .. decorator:: struct(*, align=None, layout, endian='native', pack=None) | ||
| :module: ctypes.util |
There was a problem hiding this comment.
Consider adding a collation: old syntax vs. new syntax.
There was a problem hiding this comment.
I don't think that's necessary -- the examples for Structure are right above.
Co-authored-by: Bartosz Sławecki <bartosz@ilikepython.com>
…es (pythonGH-153781) Co-authored-by: Bartosz Sławecki <bartosz@ilikepython.com>
| For controlling field-specific data, wrap the annotation in :class:`typing.Annotated` | ||
| with :class:`CFieldInfo` as the second argument, like so: |
There was a problem hiding this comment.
Maybe a silly question, but why does this use Annotated instead of dataclasses-style field: SomeType = field(anonymous=True) syntax? Did I miss a consensus on this?
There was a problem hiding this comment.
Annotated is more correct, isn't it? field() from dataclasses predates typing.Annotated, so that's why it's used there.
|
Oh, this new API looks easier to use than from ctypes.util import struct
from ctypes import c_int
@struct
class Point:
x: c_int
y: c_int
point = Point(1, 2)
print(point) |
Uh oh!
There was an error while loading. Please reload this page.