diff --git a/Lib/ctypes/_endian.py b/Lib/ctypes/_endian.py index 6382dd22b8acc8..60e2013ab69f2d 100644 --- a/Lib/ctypes/_endian.py +++ b/Lib/ctypes/_endian.py @@ -9,12 +9,13 @@ def _other_endian(typ): attributes which contain the types, for more complicated types arrays and structures are supported. """ - # check _OTHER_ENDIAN attribute (present if typ is primitive type) - if hasattr(typ, _OTHER_ENDIAN): - return getattr(typ, _OTHER_ENDIAN) + global _OTHER_ENDIAN # if typ is array if isinstance(typ, _array_type): return _other_endian(typ._type_) * typ._length_ + # check _OTHER_ENDIAN attribute (present if typ is primitive type) + if hasattr(typ, _OTHER_ENDIAN): + return getattr(typ, _OTHER_ENDIAN) # if typ is structure or union if issubclass(typ, (Structure, Union)): return typ @@ -22,14 +23,8 @@ def _other_endian(typ): class _swapped_meta: def __setattr__(self, attrname, value): - if attrname == "_fields_": - fields = [] - for desc in value: - name = desc[0] - typ = desc[1] - rest = desc[2:] - fields.append((name, _other_endian(typ)) + rest) - value = fields + if attrname == "_fields_": + value = [(desc[0], _other_endian(desc[1])) + desc[2:] for desc in value] super().__setattr__(attrname, value) class _swapped_struct_meta(_swapped_meta, type(Structure)): pass class _swapped_union_meta(_swapped_meta, type(Union)): pass diff --git a/Misc/NEWS.d/next/C_API/2024-09-24-05-12-53.gh-issue-124351.5V47DU.rst b/Misc/NEWS.d/next/C_API/2024-09-24-05-12-53.gh-issue-124351.5V47DU.rst new file mode 100644 index 00000000000000..43e9e0823de013 --- /dev/null +++ b/Misc/NEWS.d/next/C_API/2024-09-24-05-12-53.gh-issue-124351.5V47DU.rst @@ -0,0 +1,2 @@ +Improved Clarity and Correctness: The global variable _OTHER_ENDIAN is now explicitly defined for enhanced clarity and correctness in endian handling. +Optimized Code Structure: List comprehension has been implemented in the __setattr__ method to streamline the processing of value, reducing unnecessary complexity and improving readability.