Codecs

hl7types.codecs.er7.encoder.encode_er7_segment(seg, enc=EncodingChars(field='|', component='^', repetition='~', escape='\\', subcomponent='&', truncation=''))

Encode a single segment model to an ER7 segment string.

Parameters:
  • seg (BaseModel) – The segment model instance to encode.

  • enc (EncodingChars, optional) – Delimiter characters to use. Defaults to the standard HL7 encoding characters (|, ^, ~, \, &).

Returns:

A single ER7 segment string with no trailing separator, e.g. "MSA|AA|MSG001".

Return type:

str

Examples

>>> from hl7types.hl7.v2_5_1.segments import MSA
>>> from hl7types.codecs.er7.encoder import encode_er7_segment
>>> encode_er7_segment(MSA(msa_1="AA", msa_2="MSG001"))
'MSA|AA|MSG001'
hl7types.codecs.er7.encoder.encode_er7(model, segment_separator='\r')

Encode a message or segment model to an ER7 wire string.

Encoding characters are read from the delimiter-definition segment (MSH, FHS, or BHS) in the model if present, falling back to the standard HL7 defaults.

Parameters:
  • model (BaseModel) – The message, group, or segment model instance to encode.

  • segment_separator (str, optional) – Character used to join segments. The HL7 v2 specification mandates a carriage return (\r, ASCII 0x0D). Defaults to "\r".

Returns:

ER7-encoded wire string with segments joined by segment_separator. Returns an empty string if the model contains no encodable segments.

Return type:

str

Examples

>>> from hl7types.hl7.v2_5_1.segments import MSA
>>> from hl7types.codecs.er7.encoder import encode_er7
>>> encode_er7(MSA(msa_1="AA", msa_2="MSG001"))
'MSA|AA|MSG001'
hl7types.codecs.er7.decoder.decode_er7_segment(seg_str, seg_cls, enc=EncodingChars(field='|', component='^', repetition='~', escape='\\', subcomponent='&', truncation=''), *, strict=True, dt_parser=None, dtm_parser=None)

Decode a single ER7 segment string into a typed segment model.

Parameters:
  • seg_str (str) – A single ER7 segment string, e.g. "MSA|AA|MSG001".

  • seg_cls (type[BaseModel]) – The segment model class to decode into.

  • enc (EncodingChars, optional) – Delimiter characters to use for decoding. For delimiter-definition segments (MSH, FHS, BHS), the encoding characters are read from the segment string itself and override this value. Defaults to the standard HL7 encoding characters.

  • strict (bool, optional) – If True (the default), raises pydantic.ValidationError when required fields are absent. If False, missing required fields are filled with empty placeholder values and a UserWarning is emitted.

  • dt_parser (Callable[[str], str], optional) – Fallback parser for non-standard date strings in pre-v2.5 TS.1 fields (XSD base type ST). Called only when the value fails the standard HL7 DT regex. The callable receives the raw string and must return a valid HL7 DT string (e.g. "20261101"), or raise any exception to signal failure. On success a NonStandardDateWarning is emitted. Defaults to None (strict HL7 validation only).

  • dtm_parser (Callable[[str], str], optional) – Fallback parser for non-standard datetime strings in v2.5+ TS.1 fields (XSD base type DTM). Behaves identically to dt_parser but for the DTM format. Defaults to None.

Returns:

A validated instance of seg_cls.

Return type:

BaseModel

Raises:

pydantic.ValidationError – If strict=True and required fields are missing, or if any field value fails format validation, or if a fallback parser raises.

Notes

Lenient mode: When strict=False, missing required fields are filled with placeholder values (empty strings or empty dicts). The resulting segment instance is intentionally partially invalid; callers must not re-encode or serialise it without first populating missing fields.

Fallback parsers: dt_parser and dtm_parser are independent of strict. They apply only to TS.1 date/datetime fields that fail the standard HL7 regex; all other validation is unaffected.

Examples

>>> from hl7types.hl7.v2_5_1.segments import MSA
>>> from hl7types.codecs.er7.decoder import decode_er7_segment
>>> seg = decode_er7_segment("MSA|AA|MSG001", MSA)
>>> seg.msa_1
'AA'
hl7types.codecs.er7.decoder.decode_er7(wire, msg_cls=None, segment_separator='\r', *, strict=True, registry=None, dt_parser=None, dtm_parser=None)

Decode an ER7 wire string into a typed message model.

When msg_cls is not provided, the message class is resolved automatically from MSH.9 (message type) and MSH.12 (version) in the wire string. Encoding characters are read from the delimiter-definition segment in the wire and applied consistently throughout decoding.

Parameters:
  • wire (str) – A complete ER7-encoded message string with segments separated by segment_separator.

  • msg_cls (type[BaseModel], optional) – The message model class to decode into. If None, the class is resolved dynamically from MSH.9 and MSH.12.

  • segment_separator (str, optional) – Character used to split segments. Defaults to "\r".

  • strict (bool, optional) – If True, raises pydantic.ValidationError when required fields or segments are absent. If False, missing required fields are filled with empty placeholder values and a UserWarning is emitted. Defaults to True.

  • registry (HL7Registry, optional) – Registry of custom segment and message classes. Consulted when the decoder encounters a segment or message type not present in the generated specification models.

  • dt_parser (Callable[[str], str], optional) – Fallback parser for non-standard date strings in pre-v2.5 TS.1 fields. See decode_er7_segment() for full semantics.

  • dtm_parser (Callable[[str], str], optional) – Fallback parser for non-standard datetime strings in v2.5+ TS.1 fields. See decode_er7_segment() for full semantics.

Returns:

A validated instance of the resolved or provided message class.

Return type:

BaseModel

Raises:
  • ValueError – If the wire string is empty, no MSH segment is found, or the message type or version cannot be resolved to a known model class.

  • pydantic.ValidationError – If strict=True and required fields or segments are missing, if any field value fails format validation, or if a fallback parser raises.

Notes

DoS boundaries: ER7 decoding is string-split based and imposes no maximum message size or segment count. Callers that accept wire input from untrusted sources should enforce size limits before calling this function (e.g. if len(wire) > MAX_BYTES: raise ValueError).

Lenient mode: When strict=False, missing required fields and segments are filled with placeholder values (empty strings, empty dicts, or bare model_construct() instances). The resulting objects are intentionally partially invalid and must not be round-tripped through hl7types.encode_er7() or serialised to XML without first populating the missing fields.

Examples

>>> from hl7types import decode_er7
>>> wire = "MSH|^~\\&|SEND||RECV||20260101||ACK|001|P|2.5.1\rMSA|AA|001"
>>> msg = decode_er7(wire)
>>> msg.MSA.msa_1
'AA'
hl7types.codecs.xml.decoder.decode_xml_segment(elem, seg_cls, *, strict=False, truncation='', dt_parser=None, dtm_parser=None)

Decode a single XML segment element into a typed segment model.

Parameters:
  • elem (Element) – The XML element representing the segment (e.g. <MSH>).

  • seg_cls (type[BaseModel]) – The segment model class to decode into.

  • strict (bool, optional) – If True, raises pydantic.ValidationError when required fields are absent. If False, missing required fields are filled with empty placeholder values and a UserWarning is emitted. Defaults to False.

  • dt_parser (Callable[[str], str], optional) – Fallback parser for non-standard date strings in pre-v2.5 TS.1 fields. See hl7types.codecs.er7.decoder.decode_er7_segment() for full semantics.

  • dtm_parser (Callable[[str], str], optional) – Fallback parser for non-standard datetime strings in v2.5+ TS.1 fields. See hl7types.codecs.er7.decoder.decode_er7_segment() for full semantics.

Returns:

A validated instance of seg_cls.

Return type:

BaseModel

Examples

>>> from xml.etree import ElementTree as ET
>>> from hl7types.hl7.v2_5_1.segments import MSA
>>> from hl7types.codecs.xml.decoder import decode_xml_segment
>>> elem = ET.fromstring('<MSA><MSA.1>AA</MSA.1><MSA.2>MSG001</MSA.2></MSA>')
>>> seg = decode_xml_segment(elem, MSA)
>>> seg.msa_1
'AA'
hl7types.codecs.xml.decoder.decode_xml(xml_string, msg_cls=None, *, strict=True, registry=None, dt_parser=None, dtm_parser=None)

Decode an HL7 v2 XML string into a typed message or segment model.

When msg_cls is not provided, the message class is resolved automatically from MSH.9 (message type) and MSH.12 (version) inside the XML. Both namespaced (urn:hl7-org:v2xml) and bare XML are accepted.

Parameters:
  • xml_string (str) – A complete HL7 v2 XML string, including or excluding the XML declaration.

  • msg_cls (type[BaseModel], optional) – The message or segment model class to decode into. If None, the class is resolved dynamically from MSH.9 and MSH.12.

  • strict (bool, optional) – If True, raises pydantic.ValidationError when required fields or segments are absent. If False, missing required fields are filled with empty placeholder values and a UserWarning is emitted. Defaults to True.

  • registry (HL7Registry, optional) – Registry of custom segment and message classes. Consulted when the decoder encounters a segment or message type not present in the generated specification models.

  • dt_parser (Callable[[str], str], optional) – Fallback parser for non-standard date strings in pre-v2.5 TS.1 fields. See hl7types.codecs.er7.decoder.decode_er7_segment() for full semantics.

  • dtm_parser (Callable[[str], str], optional) – Fallback parser for non-standard datetime strings in v2.5+ TS.1 fields. See hl7types.codecs.er7.decoder.decode_er7_segment() for full semantics.

Returns:

A validated instance of the resolved or provided message/segment class.

Return type:

BaseModel

Raises:
  • ValueError – If the XML string is empty, no MSH element is found, or the message type or version cannot be resolved to a known model class.

  • pydantic.ValidationError – If strict=True and required fields or segments are missing, or if any field value fails format validation.

Examples

>>> from hl7types.codecs.xml.decoder import decode_xml
>>> xml = (
...     '<?xml version="1.0" encoding="UTF-8"?>'
...     '<ACK xmlns="urn:hl7-org:v2xml">'
...     '<MSH><MSH.1>|</MSH.1><MSH.2>^~\\&amp;</MSH.2>'
...     '<MSH.9><MSG.1>ACK</MSG.1></MSH.9>'
...     '<MSH.10>001</MSH.10>'
...     '<MSH.11><PT.1>P</PT.1></MSH.11>'
...     '<MSH.12><VID.1>2.5.1</VID.1></MSH.12>'
...     '<MSH.7><TS.1>20260101</TS.1></MSH.7>'
...     '</MSH>'
...     '<MSA><MSA.1>AA</MSA.1><MSA.2>001</MSA.2></MSA>'
...     '</ACK>'
... )
>>> msg = decode_xml(xml)
>>> msg.MSA.msa_1
'AA'

Fallback parsing types

class hl7types.hl7._validators.NonStandardDateWarning

Bases: UserWarning

Emitted when a fallback parser normalises a non-HL7 date/datetime value.

hl7types.DateParser

Type alias for a fallback date/datetime parser callable:

DateParser = Callable[[str], str]

The callable receives a raw non-HL7 string and must return a valid HL7 DT or DTM string, or raise any exception to signal failure. Pass instances as dt_parser= or dtm_parser= to any decode function.

See Fallback parsing for non-standard date formats for usage examples.