Pattern Matching on Record Shapes

Structural matching tests the shape of a value and can bind the fields of an accepted case where the language supports it.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Specify the handled shapes
  2. Inspect two event examples
  3. Trace a shape test through a real input
  4. Test extra, repeated, and missing information at the right level

Specify the handled shapes

An event might carry both a kind and a document identifier. A match on a delete event should recognize the required fields before using the identifier. Python mapping patterns can match even when extra keys are present. A stricter exact shape needs a separate check under the input contract.

Inspect two event examples

Try an event with the right kind and no identifier. Then try a full event with an extra timestamp. Each reveals a separate expectation about the shape. Typed input records can define how field representations are validated after a pattern match.[1][2]

Trace a shape test through a real input

An import can receive events containing an operation and a document identifier. A delete event with a document number can match a branch expecting those fields. The same operation with its document field absent cannot bind a number there. A shape match can still accept a document field whose value needs type or range validation. See structural and domain validation for where to check the additional rule.

Test extra, repeated, and missing information at the right level

Python's ordinary mapping patterns can match when the expected fields are present alongside other fields. If an API requires exactly a declared set, the shape branch needs another validation step or a schema doing that work. Add an example with a timestamp and a second example with an extra field the contract forbids.

Choose distinct operations and deliberately different field values to catch a pattern binding the wrong role. A pattern collecting remaining fields has a different intended output from one ignoring them. Fixed named records helps specify what each successful branch can expect. Verify that cases failing their shape rule can still reach a useful outcome.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩
  2. Python Software Foundation, Python Language Reference: Expressions ↩