3 ms·
Python does have the ability to create and use packed byte objects which are interoperable with C structs. The interface is even in a module in the standard lib
by ubernostrum 9y ago
Python does have the ability to create and use packed byte objects which are interoperable with C structs. The interface is even in a module in the standard library called... 'struct'.
The main issues are:
1. The C-struct interoperability is cumbersome, since really it's just byte objects with some helper functions to pack and unpack them according to a given definition (so you need both the bytes and the correct format definition in order to turn it back into native Python objects), and
2. Most people already are using one of a few different struct-like things depending on their exact use case and preference, and getting everyone to agree on a One True Struct Object to build in to Python or its standard library is probably never going to happen. Just look at namedtuples -- they were an attempt to take the most struct-like thing in Python (the tuple) and add extra optional struct-like behavior to appease people who were frustrated with the lack of structs, but of course people rant about them for having a weird internal implementation and for having behavior that makes them backwards-compatible with plain tuples.
- eesmith 9y agoctypes can also be used to create C-like structs. It has the advantage over the struct module that the elements can be accessed and modified in place.