Core API: Miscellaneous

construct.Const(subcon, value=None)

Constant field enforcing a constant value. It is used for file signatures, to validate that the given pattern exists. When parsed, the value must match.

Note that a variable length subcon may still provide positive verification. Const does not consume a precomputed amount of bytes, but depends on the subcon to read the appropriate amount. Consider for example, a field that eats null bytes and returns following byte, then compares to one. When parsing, both b”x00x00x01” and b”x01” will be parsed and checked OK.

Parameters:
  • subcon – the subcon used to build value from, or a b-string value itself
  • value – optional, the expected value
Raises:

ConstError – when parsed data does not match specified value, or building from wrong value

Example:

>>> Const(b"IHDR").build(None)
b'IHDR'
>>> Const(b"IHDR").parse(b"JPEG")
construct.core.ConstError: expected b'IHDR' but parsed b'JPEG'

>>> Const(Int32ul, 16).build(None)
b'\x10\x00\x00\x00'
construct.Computed(func)

A computed value. Underlying byte stream is unaffected. When parsing func(context) provides the value.

Parameters:func – a function that takes context and returns the computed value
Example::
>>> st = Struct(
...     "width" / Byte,
...     "height" / Byte,
...     "total" / Computed(this.width * this.height),
... )
>>> st.parse(b"12")
Container(width=49)(height=50)(total=2450)
>>> st.build(dict(width=4,height=5))
b'\x04\x05'
>>> Computed(lambda ctx: os.urandom(10)).parse(b"")
b'\x98\xc2\xec\x10\x07\xf5\x8e\x98\xc2\xec'
construct.Numpy()

Preserves numpy arrays (both shape, dtype and values).

Example:

>>> import numpy
>>> a = numpy.asarray([1,2,3])
>>> Numpy.build(a)
b"\x93NUMPY\x01\x00F\x00{'descr': '<i8', 'fortran_order': False, 'shape': (3,), }            \n\x01\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00"
>>> Numpy.parse(_)
array([1, 2, 3])
construct.NamedTuple(tuplename, tuplefields, subcon)

Both arrays, structs and sequences can be mapped to a namedtuple from collections module. To create a named tuple, you need to provide a name and a sequence of fields, either a string with space-separated names or a list of strings. Just like the standard namedtuple does.

Example:

>>> NamedTuple("coord", "x y z", Byte[3]).parse(b"123")
coord(x=49, y=50, z=51)
>>> NamedTuple("coord", "x y z", Byte >> Byte >> Byte).parse(b"123")
coord(x=49, y=50, z=51)
>>> NamedTuple("coord", "x y z", Struct("x"/Byte, "y"/Byte, "z"/Byte)).parse(b"123")
coord(x=49, y=50, z=51)
construct.Rebuild(subcon, func)

Parses the field like normal, but computes the value for building from a function. Useful for length and count fields when Prefixed and PrefixedArray cannot be used.

Example:

>>> st = Struct(
...     "count" / Rebuild(Byte, len_(this.items)),
...     "items" / Byte[this.count],
... )
>>> st.build(dict(items=[1,2,3]))
b'\x03\x01\x02\x03'
construct.Check(func)

Checks for a condition, and raises ValidationError if the check fails.

Example:

Check(lambda ctx: len(ctx.payload.data) == ctx.payload_len)

Check(len_(this.payload.data) == this.payload_len)
construct.FocusedSeq(parsebuildfrom, *subcons, **kw)

Parses and builds a sequence where only one subcon value is returned from parsing or taken into building, other fields are parsed and discarded or built from nothing. This is a replacement for SeqOfOne.

Parameters:
  • parsebuildfrom – which subcon to use, an int or str, or a context lambda returning an int or str
  • *subcons – a list of members
  • **kw – a list of members (works ONLY on python 3.6)

Excample:

>>> d = FocusedSeq("num", Const(b"MZ"), "num"/Byte, Terminated)
>>> d = FocusedSeq(1,     Const(b"MZ"), "num"/Byte, Terminated)

>>> d.parse(b"MZ\xff")
255
>>> d.build(255)
b'MZ\xff'
construct.Default(subcon, value)

Allows to make a field have a default value, which comes handly when building a Struct from a dict with missing keys.

Example:

>>> Struct("a"/Default(Byte,0)).build(dict(a=1))
b'\x01'
>>> Struct("a"/Default(Byte,0)).build(dict())
b'\x00'