Sunday, August 23, 2020

Implementing C struct-like Data Structure in Python (Requires Python 3.6+)

 The solution to implement C struct-like data structure in Python is explained in: You need the presence of dataclass python class to create a syntactically and semantically similar data structure to C struct. This class is implemented in Python 3.7. Therefore, python 3.7 is the lowest version of python supported. However, the support has been backported to Python version 3.6 (see: ). 

Perhaps, you might ask, why not just use Python collections namedtuple data type. Well, namedtuple is syntactically similar to C struct. However, it's immutable, meaning: once you have set its value, you cannot change the value. The only way to change the object value is by creating a new object with the same type and setting the value into different value.

Anyway, this is a sample usage of dataclass:  

as you can see in the screenshot above, the value of c_struc class instance can be changed (mutable), as in a C struct.

Post a Comment

No comments: