record_jar
Read and write record-jar files.
The API follows the standard library’s json module: load() and
loads() read records, and dump() and dumps() write them. See
RecordJarStrictDecoder and RecordJarStrictEncoder for the format of
draft-phillips-record-jar-02.
- class record_jar.Record(*args: Any, comment: str | None = None, **fields: Any)
Bases:
dictOne record: a
dictof field names to field bodies, with an optional comment.Decoded bodies are
str, orlistofstrwhen the decoder’srepeated_fieldsis"list". The encoders write alistortuplebody as one field for each element.It takes the same arguments as
dict, pluscomment, so a field named “comment” has to be given in a mapping:>>> Record({"Planet": "Mercury"}, comment="The first planet.") Record({'Planet': 'Mercury'}, comment='The first planet.')
Records compare equal to any mapping with the same fields, whatever their comments.
- property comment: str | None
The comment written before this record, or
None.A comment can span several lines, separated by
"\n". Any value set is converted tostr.
- class record_jar.RecordJarDecoder(comment_whitespace_separation: bool = False, continuation_string: str | bytes = '\\', field_delimiter: str | bytes = ':', record_separator: str | bytes = '', repeated_fields: str = 'last')
Bases:
objectReads the loose record-jar format from The Art of UNIX Programming.
By default, records are separated by blank lines, and fields are written
Name: body. The settings can be changed to read other variants, asRecordJarStrictDecoderdoes for draft-phillips-record-jar-02.- Parameters:
comment_whitespace_separation – whether a comment must be separated from its record separator by whitespace.
continuation_string – the string that ends a line to continue it.
field_delimiter – the string between a field name and its body.
record_separator – the text that starts a separator line between records, or
""for blank-line separators.repeated_fields – what to do with a field name that appears more than once in a record:
"last", the default, keeps only its last body, as astr;"first"keeps only its first body, as astr;"list"makes every field body alistofstr, with one element for each time the name appears, in order. SeeREPEATED_FIELDS.
- BACKSLASH_ESCAPE_REPLACEMENTS = (('\\r', '\r'), ('\\n', '\n'), ('\\t', '\t'), ('\\\\', '\\'), ('\\&', '&'))
- REPEATED_FIELDS = ('last', 'first', 'list')
- RE_ESCAPE = re.compile('\\\\[rnt\\\\&]|&#x(?P<NCR>[0-9A-Fa-f]{2,6});')
- property continuation_string: str
The string that ends a line to continue it on the next,
"\"by default. Can be set tostr, orbytesin UTF-8.
- decode(data: str | bytes, codec: CodecInfo | str | None = None) list[Record]
Read every record in
data.- Parameters:
data – record-jar text, as
str, or asbytesto be decoded.codec – the encoding to decode
byteswith, as acodecs.CodecInfoor a name. IfNone, it’s taken from a byte order mark, inferred from a UTF-16 or UTF-32 “%%”, taken from the encoding signature, or else UTF-8 (draft-phillips- record-jar-02, section 2.3).
- Raises:
RecordJarDecoderError – if
datacan’t be read.ValueError – if
codecnames an unknown encoding, or one that isn’t a text encoding.
- Returns:
A
listofRecordobjects. Records with no fields are left out.
- detect_encoding(data: str | bytes) CodecInfo | None
Return the encoding named by the encoding signature on the first line of
data, if it has one.The signature is formatted like a field after the encoding signature prefix, e.g.
%%encoding:UTF-8(draft-phillips-record-jar-02, section 2.3). It must be ASCII, sostrinput is encoded as ASCII before it’s read.The name may contain only letters, digits,
-and_(section 2), and must be a character encoding. Python’s codecs that transform text or decode backslash escapes, such asbase64,zlibandunicode_escape, aren’t character encodings, so they can’t be used.- Parameters:
data – record-jar text, as
strorbytes.- Raises:
LookupError – if the signature names an encoding Python doesn’t know, or one that can’t be used for record-jar text.
- Returns:
The
codecs.CodecInfofor the encoding, orNoneif the first line isn’t an encoding signature.
- property encoding_signature_prefix: str
The text that starts an encoding signature,
"%%"by default. Can be set tostr, orbytesin UTF-8.
- property field_delimiter: str
The string that separates a field name from its body,
":"by default. Whitespace around it is ignored. Can be set tostr, orbytesin UTF-8.
- iter_decode(data: str | bytes, codec: CodecInfo | str | None = None) Iterator[Record]
Read the records in
dataone at a time.Takes the same arguments as
decode().- Raises:
RecordJarDecoderError – if
datacan’t be read, when the record that can’t be read is reached.ValueError – if
codecnames an unknown encoding, or one that isn’t a text encoding.
- Yields:
Each
Record, with its field names asstr, and its bodies asstr, or aslistofstrifrepeated_fieldsis"list". Records with no fields are left out.
- property record_separator: str
The text that starts a separator line between records, such as
"%%", or""for blank-line separators, the default. Can be set tostr, orbytesin UTF-8.
- property repeated_fields: str
What to do with a field name that appears more than once in a record (draft-phillips-record-jar-02 allows it, and some files, such as the IANA Language Subtag Registry, rely on it):
"last", the default: each field body is astr, and a repeated name keeps only its last body."first": each field body is astr, and a repeated name keeps only its first body."list": each field body is alistofstr, with one element for each time the name appears, in order, so a field that appears once is a list of one. Every body is a list, whether its name repeats or not, so the type doesn’t depend on the input.
- exception record_jar.RecordJarDecoderError
Bases:
RecordJarErrorRecord-jar input that can’t be read.
- class record_jar.RecordJarEncoder(continuation_string: str | bytes = '\\', field_delimiter: str | bytes = ': ', fold_indentation: str | bytes | None = None, record_separator: str | bytes = '')
Bases:
objectWrites the loose record-jar format from The Art of UNIX Programming.
By default, fields are written
Name: body, and records are separated by blank lines, which can’t hold comments. The settings can be changed to write other variants, asRecordJarStrictEncoderdoes for draft-phillips-record-jar-02.- Parameters:
continuation_string – the string written at the end of a folded line to continue it.
field_delimiter – the string written between a field name and its body.
fold_indentation – the whitespace that starts each folded line, or
Noneto useINDENT_STATICwhen a line width is set, andINDENT_DYNAMICotherwise.record_separator – the text of a separator line between records, or
""for blank-line separators.
- BACKSLASH_ESCAPE_REPLACEMENTS = (('\\', '\\\\'), ('\t', '\\t'), ('\r', '\\r'), ('&', '\\&'), ('\n', '\\n'))
- INDENT_DYNAMIC = '\t'
- INDENT_STATIC = ' '
- NEWLINE_STRATEGIES = ('escape', 'fold', 'explicit_fold', 'implicit_fold', 'remove')
- NEWLINE_STRING = '\n'
- RE_ENCODING_NAME = re.compile('[A-Za-z0-9_-]+')
- RE_TOKENS = re.compile('(?:\\\\t|\\\\r|\\\\n|\\\\\\\\|&#x[\\dA-Fa-f]+;|\\S)\\s*')
- property continuation_string: str
The string written at the end of a folded line to continue it,
"\"by default. Can be set tostr, orbytesin UTF-8.
- encode(records: ~collections.abc.Iterable[~collections.abc.Mapping[object, object]], codec: ~codecs.CodecInfo = (<built-in function utf_8_encode>, <function decode>, <class 'encodings.utf_8.StreamReader'>, <class 'encodings.utf_8.StreamWriter'>), max_byte_width: int | None = None, max_character_width: int | None = None, newline_strategy: str = 'fold', encoding_signature: str | None = None, ascii_only: bool = False) str
Encode
recordsand return them as record-jar text.- Parameters:
records – an iterable of mappings of field names to field bodies, such as
Recordobjects. Names and bodies are converted tostr, and acommentattribute is written before its record. Records with no fields are skipped. A body that’s alistortupleis written as one field for each element, in order, all with the same name, as a decoder withrepeated_fields="list"reads them.codec – the encoding used to measure
max_byte_width.max_byte_width – the longest a line may be, in bytes, or
None.max_character_width – the longest a line may be, in characters, or
None.newline_strategy –
one of
NEWLINE_STRATEGIES, which chooses how line breaks in the data are written, and when a folded line ends in a continuation (\):"escape"and"fold": line breaks are escaped as\n, and a continuation is written only where a folded line ends in whitespace, which it keeps."explicit_fold": line breaks are escaped, and every folded line ends in a continuation."implicit_fold": line breaks are escaped, and no line ends in a continuation. Lines are only folded where no whitespace would be lost, andRecordJarEncoderErroris raised if there’s no such place."remove": line breaks are removed, and lines are folded as with"fold".
encoding_signature – if set, the name of the encoding the text will be saved in (e.g.
"UTF-8"), which is written as an encoding signature on the first line (draft-phillips-record-jar-02, section 2.3). Characters that encoding can’t represent are written as numeric character references (e.g."€"). The text is returned asstr, so saving it in that encoding is up to the caller.ascii_only – if
True, write every non-ASCII character as a numeric character reference, so the text is pure ASCII, the most portable form (draft-phillips-record-jar-02, section 2.3).
- Raises:
ValueError – if an argument is invalid, such as an
encoding_signaturethat isn’t the name of an encoding.RecordJarEncoderError – if a record can’t be encoded.
- Returns:
The records as record-jar text.
- property field_delimiter: str
The string written between a field name and its body,
": "in the loose encoder and" : "in the strict one. Can be set tostr, orbytesin UTF-8.
- property fold_indentation: str | None
The whitespace that starts each folded line, or
Nonefor the default:INDENT_STATICwhen a line width is set, andINDENT_DYNAMICotherwise. Can be set tostr,bytesin UTF-8, orNone.It must be whitespace, and can’t be empty or contain a line break, so folded lines are read back as part of their field.
- property record_separator: str
The text of a separator line between records, such as
"%%", or""for blank-line separators, the loose encoder’s default. Can be set tostr, orbytesin UTF-8.
- exception record_jar.RecordJarEncoderError
Bases:
RecordJarErrorA record that can’t be written in the record-jar format.
- exception record_jar.RecordJarError
Bases:
ValueErrorThe base class of
RecordJarDecoderErrorandRecordJarEncoderError.It’s a
ValueError, likejson.JSONDecodeError, since it’s raised for input that can’t be read or records that can’t be written.
- class record_jar.RecordJarStrictDecoder(continuation_string: str | bytes = '\\', field_delimiter: str | bytes = ':', repeated_fields: str = 'last')
Bases:
RecordJarDecoderReads the record-jar format of draft-phillips-record-jar-02.
Records are separated by
%%lines, comments must be separated from their%%by whitespace, and field names may not contain whitespace or:(section 2).- Parameters:
continuation_string – the string that ends a line to continue it.
field_delimiter – the string between a field name and its body.
repeated_fields – what to do with a field name that appears more than once in a record, as for
RecordJarDecoder.
- iter_decode(data: str | bytes, codec: CodecInfo | str | None = None) Iterator[Record]
Read the records in
dataone at a time, asRecordJarDecoder.iter_decode()does, and check their field names.- Raises:
RecordJarDecoderError – if
datacan’t be read, or a field name contains whitespace or:.
- class record_jar.RecordJarStrictEncoder(fold_indentation: str | bytes | None = None)
Bases:
RecordJarEncoderWrites the record-jar format of draft-phillips-record-jar-02.
Fields are written
Name : body, records are separated by%%lines, comment lines are kept to 69 characters, and the output starts with an encoding signature by default.- Parameters:
fold_indentation – the whitespace that starts each folded line, as for
RecordJarEncoder.
- MAX_COMMENT_LENGTH = 69
- encode(records: ~collections.abc.Iterable[~collections.abc.Mapping[object, object]], codec: ~codecs.CodecInfo = (<built-in function utf_8_encode>, <function decode>, <class 'encodings.utf_8.StreamReader'>, <class 'encodings.utf_8.StreamWriter'>), max_byte_width: int | None = None, max_character_width: int | None = None, newline_strategy: str = 'escape', encoding_signature: str | None = 'UTF-8', ascii_only: bool = False) str
Encode
recordsas strict record-jar text.Takes the same arguments as
RecordJarEncoder.encode(), with two differences.newline_strategyis ignored, since the strict encoder always uses"escape".encoding_signaturedefaults to"UTF-8", since the draft says files SHOULD include an encoding signature (draft-phillips-record-jar-02, section 2.3), andencoding_signature=Noneleaves it out.
- record_jar.dump(obj: Iterable[Mapping[object, object]], fp: _Writable, encoder_class: type[RecordJarEncoder] | None = None, **kwargs: Any) None
Write
obj’s records to the filefpas record-jar text.Takes the same arguments as
dumps(), plus the file. The text is written asstr, so open the file in the encoding its signature names, e.g.open(path, "w", encoding="utf-8").
- record_jar.dumps(obj: Iterable[Mapping[object, object]], encoder_class: type[RecordJarEncoder] | None = None, **kwargs: Any) str
Return
obj’s records as record-jar text.- Parameters:
obj – an iterable of mappings of field names to field bodies, such as
Recordobjects.encoder_class – the encoder to use:
RecordJarEncoder, the default, orRecordJarStrictEncoder.**kwargs – passed to the encoder’s
encode(), e.g.encoding_signatureormax_character_width.
- Raises:
RecordJarEncoderError – if a record can’t be written.
- Returns:
The records as record-jar text.
- record_jar.field_names(records: Iterable[Mapping[_Key, object]]) list[_Key]
Return every field name in
records, in the order each first appears.- Parameters:
records – an iterable of mappings, such as
Recordobjects.- Raises:
TypeError – if an element of
recordsisn’t a mapping.- Returns:
A
listof field names, each listed once.
- record_jar.load(fp: _Readable, decoder_class: type[RecordJarDecoder] | None = None, **kwargs: Any) list[Record]
Read every record in the file
fp.Takes the same arguments as
loads(), plus the file. Open the file in binary mode ("rb") to let the decoder choose its encoding.
- record_jar.loads(s: str | bytes, decoder_class: type[RecordJarDecoder] | None = None, **kwargs: Any) list[Record]
Read every record in the record-jar text
s.- Parameters:
s – record-jar text, as
str, or asbytesto be decoded.decoder_class – the decoder to use:
RecordJarDecoder, the default, orRecordJarStrictDecoder.**kwargs – passed to the decoder’s
decode(), e.g.codec.
- Raises:
RecordJarDecoderError – if
scan’t be read.- Returns:
A
listofRecordobjects.