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: dict

One record: a dict of field names to field bodies, with an optional comment.

Decoded bodies are str, or list of str when the decoder’s repeated_fields is "list". The encoders write a list or tuple body as one field for each element.

It takes the same arguments as dict, plus comment, 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 to str.

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: object

Reads 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, as RecordJarStrictDecoder does 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 a str; "first" keeps only its first body, as a str; "list" makes every field body a list of str, with one element for each time the name appears, in order. See REPEATED_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 to str, or bytes in 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 as bytes to be decoded.

  • codec – the encoding to decode bytes with, as a codecs.CodecInfo or a name. If None, 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 data can’t be read.

  • ValueError – if codec names an unknown encoding, or one that isn’t a text encoding.

Returns:

A list of Record objects. 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, so str input 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 as base64, zlib and unicode_escape, aren’t character encodings, so they can’t be used.

Parameters:

data – record-jar text, as str or bytes.

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.CodecInfo for the encoding, or None if 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 to str, or bytes in 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 to str, or bytes in UTF-8.

iter_decode(data: str | bytes, codec: CodecInfo | str | None = None) → Iterator[Record]

Read the records in data one at a time.

Takes the same arguments as decode().

Raises:
  • RecordJarDecoderError – if data can’t be read, when the record that can’t be read is reached.

  • ValueError – if codec names an unknown encoding, or one that isn’t a text encoding.

Yields:

Each Record, with its field names as str, and its bodies as str, or as list of str if repeated_fields is "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 to str, or bytes in 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 a str, and a repeated name keeps only its last body.

  • "first": each field body is a str, and a repeated name keeps only its first body.

  • "list": each field body is a list of str, 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: RecordJarError

Record-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: object

Writes 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, as RecordJarStrictEncoder does 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 None to use INDENT_STATIC when a line width is set, and INDENT_DYNAMIC otherwise.

  • 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 to str, or bytes in 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 records and return them as record-jar text.

Parameters:
  • records – an iterable of mappings of field names to field bodies, such as Record objects. Names and bodies are converted to str, and a comment attribute is written before its record. Records with no fields are skipped. A body that’s a list or tuple is written as one field for each element, in order, all with the same name, as a decoder with repeated_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, and RecordJarEncoderError is 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. "&#x20ac;"). The text is returned as str, 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_signature that 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 to str, or bytes in UTF-8.

property fold_indentation: str | None

The whitespace that starts each folded line, or None for the default: INDENT_STATIC when a line width is set, and INDENT_DYNAMIC otherwise. Can be set to str, bytes in UTF-8, or None.

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 to str, or bytes in UTF-8.

exception record_jar.RecordJarEncoderError

Bases: RecordJarError

A record that can’t be written in the record-jar format.

exception record_jar.RecordJarError

Bases: ValueError

The base class of RecordJarDecoderError and RecordJarEncoderError.

It’s a ValueError, like json.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: RecordJarDecoder

Reads 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 data one at a time, as RecordJarDecoder.iter_decode() does, and check their field names.

Raises:

RecordJarDecoderError – if data can’t be read, or a field name contains whitespace or :.

class record_jar.RecordJarStrictEncoder(fold_indentation: str | bytes | None = None)

Bases: RecordJarEncoder

Writes 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 records as strict record-jar text.

Takes the same arguments as RecordJarEncoder.encode(), with two differences. newline_strategy is ignored, since the strict encoder always uses "escape". encoding_signature defaults to "UTF-8", since the draft says files SHOULD include an encoding signature (draft-phillips-record-jar-02, section 2.3), and encoding_signature=None leaves 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 file fp as record-jar text.

Takes the same arguments as dumps(), plus the file. The text is written as str, 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 Record objects.

  • encoder_class – the encoder to use: RecordJarEncoder, the default, or RecordJarStrictEncoder.

  • **kwargs – passed to the encoder’s encode(), e.g. encoding_signature or max_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 Record objects.

Raises:

TypeError – if an element of records isn’t a mapping.

Returns:

A list of 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 as bytes to be decoded.

  • decoder_class – the decoder to use: RecordJarDecoder, the default, or RecordJarStrictDecoder.

  • **kwargs – passed to the decoder’s decode(), e.g. codec.

Raises:

RecordJarDecoderError – if s can’t be read.

Returns:

A list of Record objects.