How to construct data structure with variable size elements
<p>I am trying to construct the structure with variable size of the element <code>value</code> from class <code>val</code> : </p>

<pre><code>from construct import *

TEST = Struct("test",
           UInt8("class"),
           Embed(switch(lambda ctx: ctx.class) {
             1: UInt8("value"),
             2: UInt16("value"),
             3: UInt32("value")}
            ))
          )
</code></pre>

<p>The above code is incorrect. </p>

<p>I need to achieve something like this: If the class is 1 then one byte will be received from the packet.</p>

<p>You can use multiple <a href="https://docs.python.org/3/library/struct.html#format-characters" rel="nofollow">format string</a> to change <code>struct</code> behaviour and <code>struct.unpack_from</code> with <code>struct.calcsize</code> to continue parsing bytearray from the end of the last found byte sequence:</p>

<pre><code>import struct
v1 = bytearray([0x00,0xFF])
v2 = bytearray([0x01,0xFF,0xFF])
v3 = bytearray([0x02,0xFF,0xFF,0xFF,0xFF])

v = v2 # change this

header_format = 'B'
body_format_variants = {0:'B',1:'H',2:'L'}

header = struct.unpack_from(header_format,v,0)
body = struct.unpack_from(body_format_variants[header[0]],v,struct.calcsize(header_format))

print (header, body, "size=",struct.calcsize('&gt;'+header_format+body_format_variants[header[0]]))
</code></pre>

python construct