How can I define a python struct similar to C-like structures? I’m tired of writing code like this:
class MyStruct():
def init(self, field1, field2, field3):
self.field1 = field1
self.field2 = field2
self.field3 = field3
Is there a more convenient way to define a structure in Python?
I’ve been down this road before! If you want something straightforward and efficient, try using collections.namedtuple. It’s a lightweight way to create a class with named fields and is immutable by default. Here’s how:
from collections import namedtuple
MyStruct = namedtuple('MyStruct', ['field1', 'field2', 'field3'])
my_struct = MyStruct(field1=1, field2=2, field3=3)
This approach simplifies your code and is perfect for when you need a simple, read-only python struct!
I agree that namedtuple is great for lightweight cases! But if you need more flexibility (e.g., mutability or additional methods), Python’s dataclasses module is an even better option. It automates the creation of __init__, __repr__, and more while allowing you to define type hints.
from dataclasses import dataclass
@dataclass
class MyStruct:
field1: int
field2: int
field3: int
my_struct = MyStruct(1, 2, 3)
This approach is clean and expressive, making it ideal when working with more complex python struct-like use cases.
Those are excellent options for many use cases! However, if you’re handling packed binary data (e.g., for interfacing with C or networking), struct.Struct might be the tool you need. It replicates the functionality of a C struct by encoding data into fixed-size binary formats.
import struct
MyStruct = struct.Struct('iii') # 'i' means integer
packed_data = MyStruct.pack(1, 2, 3)
unpacked_data = MyStruct.unpack(packed_data)
This is the go-to method for low-level operations or when your python struct must directly align with binary layouts.