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, orBHS) 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, _diagnostics=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), raisespydantic.ValidationErrorwhen required fields are absent. IfFalse, missing required fields are filled with empty placeholder values and aUserWarningis emitted.dt_parser (Callable[[str], str], optional) – Fallback parser for non-standard date strings in pre-v2.5
TS.1fields (XSD base typeST). 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 aNonStandardDateWarningis emitted. Defaults toNone(strict HL7 validation only).dtm_parser (Callable[[str], str], optional) – Fallback parser for non-standard datetime strings in v2.5+
TS.1fields (XSD base typeDTM). Behaves identically todt_parserbut for the DTM format. Defaults toNone.
- Returns:
A validated instance of
seg_cls.- Return type:
BaseModel
- Raises:
pydantic.ValidationError – If
strict=Trueand 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_parseranddtm_parserare independent ofstrict. They apply only toTS.1date/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_clsis not provided, the message class is resolved automatically fromMSH.9(message type) andMSH.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 fromMSH.9andMSH.12.segment_separator (str, optional) – Character used to split segments. Defaults to
"\r".strict (bool, optional) – If
True, raisespydantic.ValidationErrorwhen required fields or segments are absent. IfFalse, missing required fields are filled with empty placeholder values and aUserWarningis emitted. Defaults toTrue.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.1fields. Seedecode_er7_segment()for full semantics.dtm_parser (Callable[[str], str], optional) – Fallback parser for non-standard datetime strings in v2.5+
TS.1fields. Seedecode_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=Trueand 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 baremodel_construct()instances). The resulting objects are intentionally partially invalid and must not be round-tripped throughhl7types.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.er7.decoder.decode_er7_from_segments(seg_strings, msg_cls, *, strict=True, registry=None, dt_parser=None, dtm_parser=None, _diagnostics=None)¶
Decode pre-split ER7 segment strings into a typed message model.
This is the segment-split-free core of
decode_er7(). It accepts the list of segment strings already produced bysplit_segments()(or retained verbatim by aGenericMessage) and performs message-class resolution, encoding-character detection, and structural decoding. Splitting the wire once and sharing the result avoids re-parsing when a caller already has the segment strings.
Hybrid ER7 decoding¶
The hybrid decoder provides two views of the same message. The generic view retains the original wire string, unknown segments, and empty values without requiring generated HL7 models. The optional typed view uses lenient decoding for known content and reports warnings or validation errors as diagnostics.
- hl7types.codecs.er7.hybrid.decode_er7_hybrid(wire, msg_cls=None, segment_separator='\r', *, registry=None, dt_parser=None, dtm_parser=None)¶
Decode ER7 losslessly and attempt to build a best-effort typed view.
The generic view always retains every received segment. The typed view uses lenient structural decoding, so unknown segments and missing required fields become diagnostics rather than preventing access to known content. Field-format validation errors and unknown message structures leave
typedasNonewhile preserving the generic view.The wire is split into segments exactly once, by the generic parse. The typed view is then built from those same segment strings rather than re-splitting the wire, so encoding detection and structural decoding share a single segmentation pass.
- class hl7types.codecs.er7.hybrid.HybridMessage¶
Bases:
BaseModelA lossless generic message with an optional typed message view.
- generic¶
- typed¶
- diagnostics¶
- model_dump_er7()¶
Return the original ER7 wire string from the generic view.
- class hl7types.codecs.er7.hybrid.HybridDecodeDiagnostic¶
Bases:
BaseModelA warning or error raised while building a typed message view.
- level¶
- message¶
Generic ER7 types¶
- class hl7types.codecs.er7.generic.GenericMessage¶
Bases:
objectA lossless, untyped ER7 message representation.
- raw¶
- segment_separator¶
- encoding¶
- segments¶
- get_segment(name)¶
- model_dump_er7()¶
Return the exact ER7 wire string supplied to the generic decoder.
- to_dict()¶
- __init__(raw, segment_separator, encoding, segments)¶
- class hl7types.codecs.er7.generic.GenericSegment¶
Bases:
objectAn untyped ER7 segment retained exactly as received.
- raw¶
- name¶
- fields¶
- get_field(position)¶
Return field at 1-based HL7 position, or None if out of range.
- to_dict()¶
- __init__(raw, name, fields)¶
- class hl7types.codecs.er7.generic.GenericField¶
Bases:
objectAn untyped ER7 field, including all repetitions and components.
- value¶
- repetitions¶
- to_dict()¶
- __init__(value, repetitions)¶
XML decoding¶
- 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, raisespydantic.ValidationErrorwhen required fields are absent. IfFalse, missing required fields are filled with empty placeholder values and aUserWarningis emitted. Defaults toFalse.dt_parser (Callable[[str], str], optional) – Fallback parser for non-standard date strings in pre-v2.5
TS.1fields. Seehl7types.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.1fields. Seehl7types.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_clsis not provided, the message class is resolved automatically fromMSH.9(message type) andMSH.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 fromMSH.9andMSH.12.strict (bool, optional) – If
True, raisespydantic.ValidationErrorwhen required fields or segments are absent. IfFalse, missing required fields are filled with empty placeholder values and aUserWarningis emitted. Defaults toTrue.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.1fields. Seehl7types.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.1fields. Seehl7types.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=Trueand 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>^~\\&</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:
UserWarningEmitted 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=ordtm_parser=to any decode function.See Fallback parsing for non-standard date formats for usage examples.