preserves/python/0.993.0/search/search_index.json

1 line
102 KiB
JSON

{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Overview","text":"<pre><code>pip install preserves\n</code></pre> <p>This package (<code>preserves</code> on pypi.org) implements Preserves for Python 3.x. It provides the core semantics as well as both the human-readable text syntax (a superset of JSON) and machine-oriented binary format (including canonicalization) for Preserves. It also implements Preserves Schema and Preserves Path.</p> <ul> <li>Main package API: preserves</li> </ul>"},{"location":"#what-is-preserves","title":"What is Preserves?","text":"<p>Preserves is a data model, with associated serialization formats.</p> <p>It supports records with user-defined labels, embedded references, and the usual suite of atomic and compound data types, including binary data as a distinct type from text strings. Its annotations allow separation of data from metadata such as comments, trace information, and provenance information.</p> <p>Preserves departs from many other data languages in defining how to compare two values. Comparison is based on the data model, not on syntax or on data structures of any particular implementation language.</p>"},{"location":"#mapping-between-preserves-values-and-python-values","title":"Mapping between Preserves values and Python values","text":"<p>Preserves <code>Value</code>s are categorized in the following way:</p> <pre><code> Value = Atom\n | Compound\n | Embedded\n\n Atom = Boolean\n | Double\n | SignedInteger\n | String\n | ByteString\n | Symbol\n\n Compound = Record\n | Sequence\n | Set\n | Dictionary\n</code></pre> <p>Python's strings, byte strings, integers, booleans, and double-precision floats stand directly for their Preserves counterparts. Wrapper objects for Symbol complete the suite of atomic types.</p> <p>Python's lists and tuples correspond to Preserves <code>Sequence</code>s, and dicts and sets to <code>Dictionary</code> and <code>Set</code> values, respectively. Preserves <code>Record</code>s are represented by Record objects. Finally, embedded values are represented by Embedded objects.</p>"},{"location":"api/","title":"The top-level preserves package","text":"<pre><code>import preserves\n</code></pre> <p>The main package re-exports a subset of the exports of its constituent modules:</p> <ul> <li> <p>From preserves.values:</p> <ul> <li>Annotated</li> <li>Embedded</li> <li>ImmutableDict</li> <li>Record</li> <li>Symbol</li> <li>annotate</li> <li>is_annotated</li> <li>preserve</li> <li>strip_annotations</li> </ul> </li> <li> <p>From preserves.error:</p> <ul> <li>DecodeError</li> <li>EncodeError</li> <li>ShortPacket</li> </ul> </li> <li> <p>From preserves.binary:</p> <ul> <li>Decoder</li> <li>Encoder</li> <li>canonicalize</li> <li>decode</li> <li>decode_with_annotations</li> <li>encode</li> </ul> </li> <li> <p>From preserves.text:</p> <ul> <li>Formatter</li> <li>Parser</li> <li>parse</li> <li>parse_with_annotations</li> <li>stringify</li> </ul> </li> <li> <p>From preserves.compare:</p> <ul> <li>cmp</li> </ul> </li> <li> <p>From preserves.merge:</p> <ul> <li>merge</li> </ul> </li> </ul> <p>It also exports the compare and fold modules themselves, permitting patterns like</p> <pre><code>&gt;&gt;&gt; from preserves import *\n&gt;&gt;&gt; compare.cmp(123, 234)\n-1\n</code></pre> <p>Finally, it provides a few utility aliases for common tasks:</p>"},{"location":"api/#preserves.dumps","title":"<code>dumps = stringify</code> <code>module-attribute</code>","text":"<p>This alias for <code>stringify</code> provides a familiar pythonesque name for converting a Preserves <code>Value</code> to a string.</p>"},{"location":"api/#preserves.loads","title":"<code>loads = parse</code> <code>module-attribute</code>","text":"<p>This alias for <code>parse</code> provides a familiar pythonesque name for converting a string to a Preserves <code>Value</code>.</p>"},{"location":"binary/","title":"Machine-oriented binary syntax","text":"<p>The preserves.binary module implements the Preserves machine-oriented binary syntax.</p> <p>The main entry points are functions encode, canonicalize, decode, and decode_with_annotations.</p> <pre><code>&gt;&gt;&gt; encode(Record(Symbol('hi'), []))\nb'\\xb4\\xb3\\x02hi\\x84'\n&gt;&gt;&gt; decode(b'\\xb4\\xb3\\x02hi\\x84')\n#hi()\n</code></pre>"},{"location":"binary/#preserves.binary.Decoder","title":"<code>Decoder(packet=b'', include_annotations=False, decode_embedded=lambda : x)</code>","text":"<p> Bases: <code>BinaryCodec</code></p> <p>Implementation of a decoder for the machine-oriented binary Preserves syntax.</p> <p>Parameters:</p> Name Type Description Default <code>packet</code> <code>bytes</code> <p>initial contents of the input buffer; may subsequently be extended by calling extend.</p> <code>b''</code> <code>include_annotations</code> <code>bool</code> <p>if <code>True</code>, wrap each value and subvalue in an Annotated object.</p> <code>False</code> <code>decode_embedded</code> <p>function accepting a <code>Value</code> and returning a possibly-decoded form of that value suitable for placing into an Embedded object.</p> <code>lambda : x</code> <p>Normal usage is to supply a buffer, and keep calling next until a ShortPacket exception is raised:</p> <pre><code>&gt;&gt;&gt; d = Decoder(b'\\xb0\\x01{\\xb1\\x05hello\\x85\\xb3\\x01x\\xb5\\x84')\n&gt;&gt;&gt; d.next()\n123\n&gt;&gt;&gt; d.next()\n'hello'\n&gt;&gt;&gt; d.next()\n()\n&gt;&gt;&gt; d.next()\nTraceback (most recent call last):\n ...\npreserves.error.ShortPacket: Short packet\n</code></pre> <p>Alternatively, keep calling try_next until it yields <code>None</code>, which is not in the domain of Preserves <code>Value</code>s:</p> <pre><code>&gt;&gt;&gt; d = Decoder(b'\\xb0\\x01{\\xb1\\x05hello\\x85\\xb3\\x01x\\xb5\\x84')\n&gt;&gt;&gt; d.try_next()\n123\n&gt;&gt;&gt; d.try_next()\n'hello'\n&gt;&gt;&gt; d.try_next()\n()\n&gt;&gt;&gt; d.try_next()\n</code></pre> <p>For convenience, Decoder implements the iterator interface, backing it with try_next, so you can simply iterate over all complete values in an input:</p> <pre><code>&gt;&gt;&gt; d = Decoder(b'\\xb0\\x01{\\xb1\\x05hello\\x85\\xb3\\x01x\\xb5\\x84')\n&gt;&gt;&gt; list(d)\n[123, 'hello', ()]\n</code></pre> <pre><code>&gt;&gt;&gt; for v in Decoder(b'\\xb0\\x01{\\xb1\\x05hello\\x85\\xb3\\x01x\\xb5\\x84'):\n... print(repr(v))\n123\n'hello'\n()\n</code></pre> <p>Supply <code>include_annotations=True</code> to read annotations alongside the annotated values:</p> <pre><code>&gt;&gt;&gt; d = Decoder(b'\\xb0\\x01{\\xb1\\x05hello\\x85\\xb3\\x01x\\xb5\\x84', include_annotations=True)\n&gt;&gt;&gt; list(d)\n[123, 'hello', @#x ()]\n</code></pre> <p>If you are incrementally reading from, say, a socket, you can use extend to add new input as if comes available:</p> <pre><code>&gt;&gt;&gt; d = Decoder(b'\\xb0\\x01{\\xb1\\x05he')\n&gt;&gt;&gt; d.try_next()\n123\n&gt;&gt;&gt; d.try_next() # returns None because the input is incomplete\n&gt;&gt;&gt; d.extend(b'llo')\n&gt;&gt;&gt; d.try_next()\n'hello'\n&gt;&gt;&gt; d.try_next()\n</code></pre> <p>Attributes:</p> Name Type Description <code>packet</code> <code>bytes</code> <p>buffered input waiting to be processed</p> <code>index</code> <code>int</code> <p>read position within <code>packet</code></p> Source code in <code>preserves/binary.py</code> <pre><code>def __init__(self, packet=b'', include_annotations=False, decode_embedded=lambda x: x):\n super(Decoder, self).__init__()\n self.packet = packet\n self.index = 0\n self.include_annotations = include_annotations\n self.decode_embedded = decode_embedded\n</code></pre>"},{"location":"binary/#preserves.binary.Decoder.extend","title":"<code>extend(data)</code>","text":"<p>Appends <code>data</code> to the remaining bytes in <code>self.packet</code>, trimming already-processed bytes from the front of <code>self.packet</code> and resetting <code>self.index</code> to zero.</p> Source code in <code>preserves/binary.py</code> <pre><code>def extend(self, data):\n \"\"\"Appends `data` to the remaining bytes in `self.packet`, trimming already-processed\n bytes from the front of `self.packet` and resetting `self.index` to zero.\"\"\"\n self.packet = self.packet[self.index:] + data\n self.index = 0\n</code></pre>"},{"location":"binary/#preserves.binary.Decoder.next","title":"<code>next()</code>","text":"<p>Reads the next complete <code>Value</code> from the internal buffer, raising ShortPacket if too few bytes are available, or DecodeError if the input is invalid somehow.</p> Source code in <code>preserves/binary.py</code> <pre><code>def next(self):\n \"\"\"Reads the next complete `Value` from the internal buffer, raising\n [ShortPacket][preserves.error.ShortPacket] if too few bytes are available, or\n [DecodeError][preserves.error.DecodeError] if the input is invalid somehow.\n\n \"\"\"\n tag = self.nextbyte()\n if tag == 0x80: return self.wrap(False)\n if tag == 0x81: return self.wrap(True)\n if tag == 0x84: raise DecodeError('Unexpected end-of-stream marker')\n if tag == 0x85:\n a = self.next()\n v = self.next()\n return self.unshift_annotation(a, v)\n if tag == 0x86:\n if self.decode_embedded is None:\n raise DecodeError('No decode_embedded function supplied')\n return self.wrap(Embedded(self.decode_embedded(self.next())))\n if tag == 0x87:\n count = self.nextbyte()\n if count == 8: return self.wrap(struct.unpack('&gt;d', self.nextbytes(8))[0])\n raise DecodeError('Invalid IEEE754 size')\n if tag == 0xb0: return self.wrap(self.nextint(self.varint()))\n if tag == 0xb1: return self.wrap(self.nextbytes(self.varint()).decode('utf-8'))\n if tag == 0xb2: return self.wrap(self.nextbytes(self.varint()))\n if tag == 0xb3: return self.wrap(Symbol(self.nextbytes(self.varint()).decode('utf-8')))\n if tag == 0xb4:\n vs = self.nextvalues()\n if not vs: raise DecodeError('Too few elements in encoded record')\n return self.wrap(Record(vs[0], vs[1:]))\n if tag == 0xb5: return self.wrap(tuple(self.nextvalues()))\n if tag == 0xb6: return self.wrap(frozenset(self.nextvalues()))\n if tag == 0xb7: return self.wrap(ImmutableDict.from_kvs(self.nextvalues()))\n raise DecodeError('Invalid tag: ' + hex(tag))\n</code></pre>"},{"location":"binary/#preserves.binary.Decoder.try_next","title":"<code>try_next()</code>","text":"<p>Like next, but returns <code>None</code> instead of raising ShortPacket.</p> Source code in <code>preserves/binary.py</code> <pre><code>def try_next(self):\n \"\"\"Like [next][preserves.binary.Decoder.next], but returns `None` instead of raising\n [ShortPacket][preserves.error.ShortPacket].\"\"\"\n start = self.index\n try:\n return self.next()\n except ShortPacket:\n self.index = start\n return None\n</code></pre>"},{"location":"binary/#preserves.binary.Encoder","title":"<code>Encoder(encode_embedded=lambda : x, canonicalize=False, include_annotations=None)</code>","text":"<p> Bases: <code>BinaryCodec</code></p> <p>Implementation of an encoder for the machine-oriented binary Preserves syntax.</p> <pre><code>&gt;&gt;&gt; e = Encoder()\n&gt;&gt;&gt; e.append(123)\n&gt;&gt;&gt; e.append('hello')\n&gt;&gt;&gt; e.append(annotate([], Symbol('x')))\n&gt;&gt;&gt; e.contents()\nb'\\xb0\\x01{\\xb1\\x05hello\\x85\\xb3\\x01x\\xb5\\x84'\n</code></pre> <p>Parameters:</p> Name Type Description Default <code>encode_embedded</code> <p>function accepting an Embedded.embeddedValue and returning a <code>Value</code> for serialization.</p> <code>lambda : x</code> <code>canonicalize</code> <code>bool</code> <p>if <code>True</code>, ensures the serialized data are in canonical form. This is slightly more work than producing potentially-non-canonical output.</p> <code>False</code> <code>include_annotations</code> <code>bool | None</code> <p>if <code>None</code>, includes annotations in the output only when <code>canonicalize</code> is <code>False</code>, because canonical serialization of values demands omission of annotations. If explicitly <code>True</code> or <code>False</code>, however, annotations will be included resp. excluded no matter the <code>canonicalize</code> setting. This can be used to get canonical ordering (<code>canonicalize=True</code>) and annotations (<code>include_annotations=True</code>).</p> <code>None</code> <p>Attributes:</p> Name Type Description <code>buffer</code> <code>bytearray</code> <p>accumulator for the output of the encoder</p> Source code in <code>preserves/binary.py</code> <pre><code>def __init__(self,\n encode_embedded=lambda x: x,\n canonicalize=False,\n include_annotations=None):\n super(Encoder, self).__init__()\n self.buffer = bytearray()\n self._encode_embedded = encode_embedded\n self._canonicalize = canonicalize\n if include_annotations is None:\n self.include_annotations = not self._canonicalize\n else:\n self.include_annotations = include_annotations\n</code></pre>"},{"location":"binary/#preserves.binary.Encoder.append","title":"<code>append(v)</code>","text":"<p>Extend <code>self.buffer</code> with an encoding of <code>v</code>.</p> Source code in <code>preserves/binary.py</code> <pre><code>def append(self, v):\n \"\"\"Extend `self.buffer` with an encoding of `v`.\"\"\"\n v = preserve(v)\n if hasattr(v, '__preserve_write_binary__'):\n v.__preserve_write_binary__(self)\n elif v is False:\n self.buffer.append(0x80)\n elif v is True:\n self.buffer.append(0x81)\n elif isinstance(v, float):\n self.buffer.append(0x87)\n self.buffer.append(8)\n self.buffer.extend(struct.pack('&gt;d', v))\n elif isinstance(v, numbers.Number):\n self.encodeint(v)\n elif isinstance(v, bytes):\n self.encodebytes(0xb2, v)\n elif isinstance(v, basestring_):\n self.encodebytes(0xb1, v.encode('utf-8'))\n elif isinstance(v, list):\n self.encodevalues(0xb5, v)\n elif isinstance(v, tuple):\n self.encodevalues(0xb5, v)\n elif isinstance(v, set):\n self.encodeset(v)\n elif isinstance(v, frozenset):\n self.encodeset(v)\n elif isinstance(v, dict):\n self.encodedict(v)\n else:\n try:\n i = iter(v)\n except TypeError:\n i = None\n if i is None:\n self.cannot_encode(v)\n else:\n self.encodevalues(0xb5, i)\n</code></pre>"},{"location":"binary/#preserves.binary.Encoder.contents","title":"<code>contents()</code>","text":"<p>Returns a <code>bytes</code> constructed from the contents of <code>self.buffer</code>.</p> Source code in <code>preserves/binary.py</code> <pre><code>def contents(self):\n \"\"\"Returns a `bytes` constructed from the contents of `self.buffer`.\"\"\"\n return bytes(self.buffer)\n</code></pre>"},{"location":"binary/#preserves.binary.Encoder.reset","title":"<code>reset()</code>","text":"<p>Clears <code>self.buffer</code> to a fresh empty <code>bytearray</code>.</p> Source code in <code>preserves/binary.py</code> <pre><code>def reset(self):\n \"\"\"Clears `self.buffer` to a fresh empty `bytearray`.\"\"\"\n self.buffer = bytearray()\n</code></pre>"},{"location":"binary/#preserves.binary.canonicalize","title":"<code>canonicalize(v, **kwargs)</code>","text":"<p>As encode, but sets <code>canonicalize=True</code> in the Encoder constructor.</p> Source code in <code>preserves/binary.py</code> <pre><code>def canonicalize(v, **kwargs):\n \"\"\"As [encode][preserves.binary.encode], but sets `canonicalize=True` in the\n [Encoder][preserves.binary.Encoder] constructor.\n\n \"\"\"\n return encode(v, canonicalize=True, **kwargs)\n</code></pre>"},{"location":"binary/#preserves.binary.decode","title":"<code>decode(bs, **kwargs)</code>","text":"<p>Yields the first complete encoded value from <code>bs</code>, passing <code>kwargs</code> through to the Decoder constructor. Raises exceptions as per next.</p> <p>Parameters:</p> Name Type Description Default <code>bs</code> <code>bytes</code> <p>encoded data to decode</p> required Source code in <code>preserves/binary.py</code> <pre><code>def decode(bs, **kwargs):\n \"\"\"Yields the first complete encoded value from `bs`, passing `kwargs` through to the\n [Decoder][preserves.binary.Decoder] constructor. Raises exceptions as per\n [next][preserves.binary.Decoder.next].\n\n Args:\n bs (bytes): encoded data to decode\n\n \"\"\"\n return Decoder(packet=bs, **kwargs).next()\n</code></pre>"},{"location":"binary/#preserves.binary.decode_with_annotations","title":"<code>decode_with_annotations(bs, **kwargs)</code>","text":"<p>Like decode, but supplying <code>include_annotations=True</code> to the Decoder constructor.</p> Source code in <code>preserves/binary.py</code> <pre><code>def decode_with_annotations(bs, **kwargs):\n \"\"\"Like [decode][preserves.binary.decode], but supplying `include_annotations=True` to the\n [Decoder][preserves.binary.Decoder] constructor.\"\"\"\n return Decoder(packet=bs, include_annotations=True, **kwargs).next()\n</code></pre>"},{"location":"binary/#preserves.binary.encode","title":"<code>encode(v, **kwargs)</code>","text":"<p>Encode a single <code>Value</code> <code>v</code> to a byte string. Any supplied <code>kwargs</code> are passed on to the underlying Encoder constructor.</p> Source code in <code>preserves/binary.py</code> <pre><code>def encode(v, **kwargs):\n \"\"\"Encode a single `Value` `v` to a byte string. Any supplied `kwargs` are passed on to the\n underlying [Encoder][preserves.binary.Encoder] constructor.\"\"\"\n e = Encoder(**kwargs)\n e.append(v)\n return e.contents()\n</code></pre>"},{"location":"compare/","title":"Comparing Values","text":"<p>Preserves specifies a total ordering and an equivalence between terms. The preserves.compare module implements the ordering and equivalence relations.</p> <pre><code>&gt;&gt;&gt; cmp(\"bzz\", \"c\")\n-1\n&gt;&gt;&gt; cmp(True, [])\n-1\n&gt;&gt;&gt; lt(\"bzz\", \"c\")\nTrue\n&gt;&gt;&gt; eq(\"bzz\", \"c\")\nFalse\n</code></pre> <p>Note that the ordering relates more values than Python's built-in ordering:</p> <pre><code>&gt;&gt;&gt; [1, 2, 2] &lt; [1, 2, \"3\"]\nTraceback (most recent call last):\n ..\nTypeError: '&lt;' not supported between instances of 'int' and 'str'\n\n&gt;&gt;&gt; lt([1, 2, 2], [1, 2, \"3\"])\nTrue\n</code></pre>"},{"location":"compare/#preserves.compare.cmp","title":"<code>cmp(a, b)</code>","text":"<p>Returns <code>-1</code> if <code>a</code> &lt; <code>b</code>, or <code>0</code> if <code>a</code> = <code>b</code>, or <code>1</code> if <code>a</code> &gt; <code>b</code> according to the Preserves total order.</p> Source code in <code>preserves/compare.py</code> <pre><code>def cmp(a, b):\n \"\"\"Returns `-1` if `a` &lt; `b`, or `0` if `a` = `b`, or `1` if `a` &gt; `b` according to the\n [Preserves total order](https://preserves.dev/preserves.html#total-order).\"\"\"\n return _cmp(preserve(a), preserve(b))\n</code></pre>"},{"location":"compare/#preserves.compare.eq","title":"<code>eq(a, b)</code>","text":"<p>Returns <code>True</code> iff <code>a</code> = <code>b</code> according to the Preserves equivalence relation.</p> Source code in <code>preserves/compare.py</code> <pre><code>def eq(a, b):\n \"\"\"Returns `True` iff `a` = `b` according to the [Preserves equivalence\n relation](https://preserves.dev/preserves.html#equivalence).\"\"\"\n return _eq(preserve(a), preserve(b))\n</code></pre>"},{"location":"compare/#preserves.compare.le","title":"<code>le(a, b)</code>","text":"<p>Returns <code>True</code> iff <code>a</code> \u2264 <code>b</code> according to the Preserves total order.</p> Source code in <code>preserves/compare.py</code> <pre><code>def le(a, b):\n \"\"\"Returns `True` iff `a` \u2264 `b` according to the [Preserves total\n order](https://preserves.dev/preserves.html#total-order).\"\"\"\n return cmp(a, b) &lt;= 0\n</code></pre>"},{"location":"compare/#preserves.compare.lt","title":"<code>lt(a, b)</code>","text":"<p>Returns <code>True</code> iff <code>a</code> &lt; <code>b</code> according to the Preserves total order.</p> Source code in <code>preserves/compare.py</code> <pre><code>def lt(a, b):\n \"\"\"Returns `True` iff `a` &lt; `b` according to the [Preserves total\n order](https://preserves.dev/preserves.html#total-order).\"\"\"\n return cmp(a, b) &lt; 0\n</code></pre>"},{"location":"compare/#preserves.compare.sorted","title":"<code>sorted(iterable, *, key=lambda : x, reverse=False)</code>","text":"<p>Returns a sorted list built from <code>iterable</code>, extracting a sort key using <code>key</code>, and ordering according to the Preserves total order. Directly analogous to the built-in Python <code>sorted</code> routine, except uses the Preserves order instead of Python's less-than relation.</p> Source code in <code>preserves/compare.py</code> <pre><code>def sorted(iterable, *, key=lambda x: x, reverse=False):\n \"\"\"Returns a sorted list built from `iterable`, extracting a sort key using `key`, and\n ordering according to the [Preserves total\n order](https://preserves.dev/preserves.html#total-order). Directly analogous to the\n [built-in Python `sorted`\n routine](https://docs.python.org/3/library/functions.html#sorted), except uses the\n Preserves order instead of Python's less-than relation.\n\n \"\"\"\n return _sorted(iterable, key=lambda x: _key(key(x)), reverse=reverse)\n</code></pre>"},{"location":"compare/#preserves.compare.sorted_items","title":"<code>sorted_items(d)</code>","text":"<p>Given a dictionary <code>d</code>, yields a list of <code>(key, value)</code> tuples sorted by <code>key</code>.</p> Source code in <code>preserves/compare.py</code> <pre><code>def sorted_items(d):\n \"\"\"Given a dictionary `d`, yields a list of `(key, value)` tuples sorted by `key`.\"\"\"\n return sorted(d.items(), key=_item_key)\n</code></pre>"},{"location":"error/","title":"Codec errors","text":"<p>The preserves.error module exports various <code>Error</code> subclasses.</p>"},{"location":"error/#preserves.error.DecodeError","title":"<code>DecodeError</code>","text":"<p> Bases: <code>ValueError</code></p> <p>Raised whenever preserves.binary.Decoder or preserves.text.Parser detect invalid input.</p>"},{"location":"error/#preserves.error.EncodeError","title":"<code>EncodeError</code>","text":"<p> Bases: <code>ValueError</code></p> <p>Raised whenever preserves.binary.Encoder or preserves.text.Formatter are unable to proceed.</p>"},{"location":"error/#preserves.error.ShortPacket","title":"<code>ShortPacket</code>","text":"<p> Bases: <code>DecodeError</code></p> <p>Raised whenever preserves.binary.Decoder or preserves.text.Parser discover that they want to read beyond the end of the currently-available input buffer in order to completely read an encoded value.</p>"},{"location":"fold/","title":"Traversing values","text":"<p>The preserves.fold module exports various utilities for traversing compound <code>Value</code>s.</p>"},{"location":"fold/#preserves.fold.map_embeddeds","title":"<code>map_embeddeds(f, v)</code>","text":"<p>Returns an equivalent copy of <code>v</code>, except where each contained Embedded value is replaced by <code>f</code> applied to the Embedded's <code>embeddedValue</code> attribute.</p> <pre><code>&gt;&gt;&gt; map_embeddeds(lambda w: Embedded(f'w={w}'), ['a', Embedded(123), {'z': 6.0}])\n('a', #!'w=123', {'z': 6.0})\n</code></pre> Source code in <code>preserves/fold.py</code> <pre><code>def map_embeddeds(f, v):\n \"\"\"Returns an [equivalent][preserves.compare.eq] copy of `v`, except where each contained\n [Embedded][preserves.values.Embedded] value is replaced by `f` applied to the Embedded's\n `embeddedValue` attribute.\n\n ```python\n &gt;&gt;&gt; map_embeddeds(lambda w: Embedded(f'w={w}'), ['a', Embedded(123), {'z': 6.0}])\n ('a', #!'w=123', {'z': 6.0})\n\n ```\n \"\"\"\n def walk(v):\n if isinstance(v, Embedded):\n return f(v.embeddedValue)\n elif isinstance(v, (list, tuple)):\n return tuple(walk(w) for w in v)\n elif isinstance(v, (set, frozenset)):\n return frozenset(walk(w) for w in v)\n elif isinstance(v, dict):\n return ImmutableDict.from_kvs(walk(w) for w in dict_kvs(v))\n elif isinstance(v, Record):\n return Record(walk(v.key), walk(v.fields))\n else:\n return v\n return walk(v)\n</code></pre>"},{"location":"merge/","title":"Merging values","text":"<p>The preserves.merge module exports various utilities for merging <code>Value</code>s.</p>"},{"location":"merge/#preserves.merge.merge","title":"<code>merge(v0, *vs, merge_embedded=None)</code>","text":"<p>Repeatedly merges <code>v0</code> with each element in <code>vs</code> using merge2, returning the final result. The <code>merge_embedded</code> parameter is passed on to merge2.</p> Source code in <code>preserves/merge.py</code> <pre><code>def merge(v0, *vs, merge_embedded=None):\n \"\"\"Repeatedly merges `v0` with each element in `vs` using [merge2][preserves.merge.merge2],\n returning the final result. The `merge_embedded` parameter is passed on to merge2.\"\"\"\n v = v0\n for vN in vs:\n v = merge2(v, vN, merge_embedded=merge_embedded)\n return v\n</code></pre>"},{"location":"merge/#preserves.merge.merge2","title":"<code>merge2(a, b, merge_embedded=None)</code>","text":"<p>Merges <code>a</code> and <code>b</code>, returning the result. Raises <code>ValueError</code> if, during the merge, a pair of incompatible values is discovered.</p> <p>If <code>a</code> and <code>b</code> are Embedded objects, their <code>embeddedValue</code>s are merged using <code>merge_embedded</code>, and the result is again wrapped in an Embedded object.</p> <pre><code>&gt;&gt;&gt; merge2(123, 234)\nTraceback (most recent call last):\n ...\nValueError: Cannot merge items\n&gt;&gt;&gt; merge2(123, 123)\n123\n&gt;&gt;&gt; merge2('hi', 0)\nTraceback (most recent call last):\n ...\nValueError: Cannot merge items\n&gt;&gt;&gt; merge2([1, 2], [1, 2])\n[1, 2]\n&gt;&gt;&gt; merge2([1, 2], [1, 3])\nTraceback (most recent call last):\n ...\nValueError: Cannot merge items\n&gt;&gt;&gt; merge2({'a': 1, 'b': 2}, {'a': 1, 'c': 3})\n{'a': 1, 'b': 2, 'c': 3}\n&gt;&gt;&gt; merge2({'a': 1, 'b': 2}, {'a': 10, 'c': 3})\nTraceback (most recent call last):\n ...\nValueError: Cannot merge items\n&gt;&gt;&gt; merge2(Record('a', [1, {'x': 2}]), Record('a', [1, {'y': 3}]))\n'a'(1, {'x': 2, 'y': 3})\n</code></pre> Source code in <code>preserves/merge.py</code> <pre><code>def merge2(a, b, merge_embedded=None):\n \"\"\"Merges `a` and `b`, returning the result. Raises `ValueError` if, during the merge, a\n pair of incompatible values is discovered.\n\n If `a` and `b` are [Embedded][preserves.values.Embedded] objects, their `embeddedValue`s\n are merged using `merge_embedded`, and the result is again wrapped in an\n [Embedded][preserves.values.Embedded] object.\n\n ```python\n &gt;&gt;&gt; merge2(123, 234)\n Traceback (most recent call last):\n ...\n ValueError: Cannot merge items\n &gt;&gt;&gt; merge2(123, 123)\n 123\n &gt;&gt;&gt; merge2('hi', 0)\n Traceback (most recent call last):\n ...\n ValueError: Cannot merge items\n &gt;&gt;&gt; merge2([1, 2], [1, 2])\n [1, 2]\n &gt;&gt;&gt; merge2([1, 2], [1, 3])\n Traceback (most recent call last):\n ...\n ValueError: Cannot merge items\n &gt;&gt;&gt; merge2({'a': 1, 'b': 2}, {'a': 1, 'c': 3})\n {'a': 1, 'b': 2, 'c': 3}\n &gt;&gt;&gt; merge2({'a': 1, 'b': 2}, {'a': 10, 'c': 3})\n Traceback (most recent call last):\n ...\n ValueError: Cannot merge items\n &gt;&gt;&gt; merge2(Record('a', [1, {'x': 2}]), Record('a', [1, {'y': 3}]))\n 'a'(1, {'x': 2, 'y': 3})\n\n ```\n\n \"\"\"\n if a == b:\n return a\n if isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)):\n return merge_seq(a, b)\n if isinstance(a, (set, frozenset)) and isinstance(b, (set, frozenset)):\n _die()\n if isinstance(a, dict) and isinstance(b, dict):\n r = {}\n for (ak, av) in a.items():\n bv = b.get(ak, None)\n r[ak] = av if bv is None else merge2(av, bv, merge_embedded=merge_embedded)\n for (bk, bv) in b.items():\n if bk not in r:\n r[bk] = bv\n return r\n if isinstance(a, Record) and isinstance(b, Record):\n return Record(merge2(a.key, b.key, merge_embedded=merge_embedded),\n merge_seq(a.fields, b.fields, merge_embedded=merge_embedded))\n if isinstance(a, Embedded) and isinstance(b, Embedded):\n m = (merge_embedded or merge_embedded_id)(a.embeddedValue, b.embeddedValue)\n if m is None: _die()\n return Embedded(m)\n _die()\n</code></pre>"},{"location":"path/","title":"Preserves Path","text":"<p>The preserves.path module implements Preserves Path.</p> <p>Preserves Path is roughly analogous to XPath, but for Preserves values: just as XPath selects portions of an XML document, a Preserves Path uses path expressions to select portions of a <code>Value</code>.</p> <p>Use parse to compile a path expression, and then use the exec method on the result to apply it to a given input:</p> <pre><code>parse(PATH_EXPRESSION_STRING).exec(PRESERVES_VALUE)\n -&gt; SEQUENCE_OF_PRESERVES_VALUES\n</code></pre>"},{"location":"path/#preserves.path--command-line-usage","title":"Command-line usage","text":"<p>When preserves.path is run as a <code>__main__</code> module, <code>sys.argv[1]</code> is parsed, interpreted as a path expression, and run against human-readable values read from standard input. Each matching result is passed to stringify and printed to standard output.</p>"},{"location":"path/#preserves.path--examples","title":"Examples","text":""},{"location":"path/#preserves.path--setup-loading-test-data","title":"Setup: Loading test data","text":"<p>The following examples use <code>testdata</code>:</p> <pre><code>&gt;&gt;&gt; with open('tests/samples.bin', 'rb') as f:\n... testdata = decode_with_annotations(f.read())\n</code></pre> <p>Recall that <code>samples.bin</code> contains a binary-syntax form of the human-readable [<code>samples.pr](https://preserves.dev/tests/samples.pr) test data file, intended to exercise most of the features of Preserves. In particular, the root</code>Value` in the file has a number of annotations (for documentation and other purposes).</p>"},{"location":"path/#preserves.path--example-1-selecting-string-valued-documentation-annotations","title":"Example 1: Selecting string-valued documentation annotations","text":"<p>The path expression <code>.annotations ^ Documentation . 0 / string</code> proceeds in five steps:</p> <ol> <li><code>.annotations</code> selects each annotation on the root document</li> <li><code>^ Documentation</code> retains only those values (each an annotation of the root) that are <code>Record</code>s with label equal to the symbol <code>Documentation</code></li> <li><code>. 0</code> moves into the first child (the first field) of each such <code>Record</code>, which in our case is a list of other <code>Value</code>s</li> <li><code>/</code> selects all immediate children of these lists</li> <li><code>string</code> retains only those values that are strings</li> </ol> <p>The result of evaluating it on <code>testdata</code> is as follows:</p> <pre><code>&gt;&gt;&gt; selector = parse('.annotations ^ Documentation . 0 / string')\n&gt;&gt;&gt; for result in selector.exec(testdata):\n... print(stringify(result))\n\"Individual test cases may be any of the following record types:\"\n\"In each test, let stripped = strip(annotatedValue),\"\n\" encodeBinary(\u00b7) produce canonical ordering and no annotations,\"\n\" looseEncodeBinary(\u00b7) produce any ordering, but with annotations,\"\n\" annotatedBinary(\u00b7) produce canonical ordering, but with annotations,\"\n\" decodeBinary(\u00b7) include annotations,\"\n\" encodeText(\u00b7) include annotations,\"\n\" decodeText(\u00b7) include annotations,\"\n\"and check the following numbered expectations according to the table above:\"\n\"Implementations may vary in their treatment of the difference between expectations\"\n\"21/22 and 31/32, depending on how they wish to treat end-of-stream conditions.\"\n</code></pre>"},{"location":"path/#preserves.path--example-2-selecting-tests-with-records-as-their-annotatedvalues","title":"Example 2: Selecting tests with Records as their annotatedValues","text":"<p>The path expression <code>// [.^ [= Test + = NondeterministicTest]] [. 1 rec]</code> proceeds in three steps:</p> <ol> <li> <p><code>//</code> recursively decomposes the input, yielding all direct and indirect descendants of each input value</p> </li> <li> <p><code>[.^ [= Test + = NondeterministicTest]]</code> retains only those inputs (each a descendant of the root) that yield more than zero results when executed against the expression within the brackets:</p> <ol> <li><code>.^</code> selects only labels of values that are <code>Records</code>, filtering by type and transforming in a single step</li> <li><code>[= Test + = NondeterministicTest]</code> again filters by a path expression:<ol> <li>the infix <code>+</code> operator takes the union of matches of its arguments</li> <li>the left-hand argument, <code>= Test</code> selects values (remember, record labels) equal to the symbol <code>Test</code></li> <li>the right-hand argument <code>= NondeterministicTest</code> selects values equal to <code>NondeterministicTest</code></li> </ol> </li> </ol> <p>The result is thus all <code>Record</code>s anywhere inside <code>testdata</code> that have either <code>Test</code> or <code>NondeterministicTest</code> as their labels.</p> </li> <li> <p><code>[. 1 rec]</code> filters these <code>Record</code>s by another path expression:</p> <ol> <li><code>. 1</code> selects their second field (fields are numbered from 0)</li> <li><code>rec</code> retains only values that are <code>Record</code>s</li> </ol> </li> </ol> <p>Evaluating the expression against <code>testdata</code> yields the following:</p> <pre><code>&gt;&gt;&gt; selector = parse('// [.^ [= Test + = NondeterministicTest]] [. 1 rec]')\n&gt;&gt;&gt; for result in selector.exec(testdata):\n... print(stringify(result))\n&lt;Test #[tLMHY2FwdHVyZbSzB2Rpc2NhcmSEhA==] &lt;capture &lt;discard&gt;&gt;&gt;\n&lt;Test #[tLMHb2JzZXJ2ZbSzBXNwZWFrtLMHZGlzY2FyZIS0swdjYXB0dXJltLMHZGlzY2FyZISEhIQ=] &lt;observe &lt;speak &lt;discard&gt; &lt;capture &lt;discard&gt;&gt;&gt;&gt;&gt;\n&lt;Test #[tLWzBnRpdGxlZLMGcGVyc29usAECswV0aGluZ7ABAYSwAWWxCUJsYWNrd2VsbLSzBGRhdGWwAgcdsAECsAEDhLECRHKE] &lt;[titled person 2 thing 1] 101 \"Blackwell\" &lt;date 1821 2 3&gt; \"Dr\"&gt;&gt;\n&lt;Test #[tLMHZGlzY2FyZIQ=] &lt;discard&gt;&gt;\n&lt;Test #[tLABB7WEhA==] &lt;7 []&gt;&gt;\n&lt;Test #[tLMHZGlzY2FyZLMIc3VycHJpc2WE] &lt;discard surprise&gt;&gt;\n&lt;Test #[tLEHYVN0cmluZ7ABA7ABBIQ=] &lt;\"aString\" 3 4&gt;&gt;\n&lt;Test #[tLSzB2Rpc2NhcmSEsAEDsAEEhA==] &lt;&lt;discard&gt; 3 4&gt;&gt;\n&lt;Test #[hbMCYXK0swFShbMCYWazAWaE] @ar &lt;R @af f&gt;&gt;\n&lt;Test #[tIWzAmFyswFShbMCYWazAWaE] &lt;@ar R @af f&gt;&gt;\n</code></pre>"},{"location":"path/#preserves.path.Predicate","title":"<code>Predicate = syntax.Predicate</code> <code>module-attribute</code>","text":"<p>Schema definition for representing a Preserves Path <code>Predicate</code>.</p>"},{"location":"path/#preserves.path.Selector","title":"<code>Selector = syntax.Selector</code> <code>module-attribute</code>","text":"<p>Schema definition for representing a sequence of Preserves Path <code>Step</code>s.</p>"},{"location":"path/#preserves.path.syntax","title":"<code>syntax = load_schema_file(pathlib.Path(__file__).parent / 'path.prb').path</code> <code>module-attribute</code>","text":"<p>This value is a Python representation of a Preserves Schema definition for the Preserves Path expression language. The language is defined in the file path.prs.</p>"},{"location":"path/#preserves.path.exec","title":"<code>exec(self, v)</code>","text":"<p>WARNING: This is not a function: it is a method on Selector, Predicate, and so on.</p> <pre><code>&gt;&gt;&gt; sel = parse('/ [.length gt 1]')\n&gt;&gt;&gt; sel.exec(['', 'a', 'ab', 'abc', 'abcd', 'bcd', 'cd', 'd', ''])\n('ab', 'abc', 'abcd', 'bcd', 'cd')\n</code></pre> Source code in <code>preserves/path.py</code> <pre><code>@extend(syntax.Function)\ndef exec(self, v):\n \"\"\"WARNING: This is not a *function*: it is a *method* on\n [Selector][preserves.path.Selector], [Predicate][preserves.path.Predicate], and so on.\n\n ```python\n &gt;&gt;&gt; sel = parse('/ [.length gt 1]')\n &gt;&gt;&gt; sel.exec(['', 'a', 'ab', 'abc', 'abcd', 'bcd', 'cd', 'd', ''])\n ('ab', 'abc', 'abcd', 'bcd', 'cd')\n\n ```\n\n \"\"\"\n return (len(self.selector.exec(v)),)\n</code></pre>"},{"location":"path/#preserves.path.parse","title":"<code>parse(s)</code>","text":"<p>Parse <code>s</code> as a Preserves Path path expression, yielding a Selector object. Selectors (and Predicates etc.) have an exec method defined on them.</p> <p>Raises <code>ValueError</code> if <code>s</code> is not a valid path expression.</p> Source code in <code>preserves/path.py</code> <pre><code>def parse(s):\n \"\"\"Parse `s` as a Preserves Path path expression, yielding a\n [Selector][preserves.path.Selector] object. Selectors (and Predicates etc.) have an\n [exec][preserves.path.exec] method defined on them.\n\n Raises `ValueError` if `s` is not a valid path expression.\n\n \"\"\"\n return parse_selector(Parser(s))\n</code></pre>"},{"location":"schema/","title":"Preserves Schema","text":"<p>A Preserves schema connects Preserves <code>Value</code>s to host-language data structures. Each definition within a schema can be processed by a compiler to produce</p> <ul> <li> <p>a simple host-language type definition;</p> </li> <li> <p>a partial parsing function from <code>Value</code>s to instances of the produced type; and</p> </li> <li> <p>a total serialization function from instances of the type to <code>Value</code>s.</p> </li> </ul> <p>Every parsed <code>Value</code> retains enough information to always be able to be serialized again, and every instance of a host-language data structure contains, by construction, enough information to be successfully serialized.</p>"},{"location":"schema/#schema-support-in-python","title":"Schema support in Python","text":"<p>The preserves.schema module implements Preserves Schema for Python.</p> <p>A Schema source file (like this one) is first compiled using <code>preserves-schemac</code> to produce a binary-syntax schema bundle containing schema module definitons (like this one). Python code then loads the bundle, exposing its contents as Namespaces ultimately containing SchemaObjects.</p>"},{"location":"schema/#preserves.schema--examples","title":"Examples","text":""},{"location":"schema/#preserves.schema--setup-loading-a-schema-bundle","title":"Setup: Loading a schema bundle","text":"<p>For our running example, we will use schemas associated with the Syndicated Actor Model. (The schema bundle is a copy of this file from the <code>syndicate-protocols</code> repository.)</p> <p>To load a schema bundle, use load_schema_file (or, alternatively, use Compiler directly):</p> <pre><code>&gt;&gt;&gt; bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')\n&gt;&gt;&gt; type(bundle)\n&lt;class 'preserves.schema.Namespace'&gt;\n</code></pre> <p>The top-level entries in the loaded bundle are schema modules. Let's examine the <code>stream</code> schema module, whose source code indicates that it should contain definitions for <code>Mode</code>, <code>Source</code>, <code>Sink</code>, etc.:</p> <pre><code>&gt;&gt;&gt; bundle.stream # doctest: +ELLIPSIS\n{'Mode': &lt;class 'stream.Mode'&gt;, 'Sink': &lt;class 'stream.Sink'&gt;, ...}\n</code></pre>"},{"location":"schema/#preserves.schema--example-1-streamstreamlistenererror-a-product-type","title":"Example 1: stream.StreamListenerError, a product type","text":"<p>Drilling down further, let's consider the definition of StreamListenerError, which appears in the source as</p> <pre><code>StreamListenerError = &lt;stream-listener-error @spec any @message string&gt; .\n</code></pre> <p>This reads, in the Preserves Schema language, as the definition of a simple product type (record, class, object) with two named fields <code>spec</code> and <code>message</code>. Parsing a value into a <code>StreamListenerError</code> will only succeed if it's a record, if the label matches, the second field (<code>message</code>) is a string, and it has exactly two fields.</p> <pre><code>&gt;&gt;&gt; bundle.stream.StreamListenerError\n&lt;class 'stream.StreamListenerError'&gt;\n</code></pre> <p>The <code>StreamListenerError</code> class includes a decode method that analyzes an input value:</p> <pre><code>&gt;&gt;&gt; bundle.stream.StreamListenerError.decode(\n... parse('&lt;stream-listener-error &lt;xyz&gt; \"an error\"&gt;'))\nStreamListenerError {'spec': #xyz(), 'message': 'an error'}\n</code></pre> <p>If invalid input is supplied, decode will raise SchemaDecodeFailed, which includes helpful information for diagnosing the problem (as we will see below, this is especially useful for parsers for sum types):</p> <pre><code>&gt;&gt;&gt; bundle.stream.StreamListenerError.decode(\n... parse('&lt;i-am-invalid&gt;'))\nTraceback (most recent call last):\n ...\npreserves.schema.SchemaDecodeFailed: Could not decode i-am-invalid using &lt;class 'stream.StreamListenerError'&gt;\nMost likely reason: in stream.StreamListenerError: &lt;lit stream-listener-error&gt; didn't match i-am-invalid\nFull explanation: \n in stream.StreamListenerError: &lt;lit stream-listener-error&gt; didn't match i-am-invalid\n</code></pre> <p>Alternatively, the try_decode method catches SchemaDecodeFailed, transforming it into <code>None</code>:</p> <pre><code>&gt;&gt;&gt; bundle.stream.StreamListenerError.try_decode(\n... parse('&lt;stream-listener-error &lt;xyz&gt; \"an error\"&gt;'))\nStreamListenerError {'spec': #xyz(), 'message': 'an error'}\n&gt;&gt;&gt; bundle.stream.StreamListenerError.try_decode(\n... parse('&lt;i-am-invalid&gt;'))\n</code></pre> <p>The class can also be instantiated directly:</p> <pre><code>&gt;&gt;&gt; err = bundle.stream.StreamListenerError(Record(Symbol('xyz'), []), 'an error')\n&gt;&gt;&gt; err\nStreamListenerError {'spec': #xyz(), 'message': 'an error'}\n</code></pre> <p>The fields and contents of instances can be queried:</p> <pre><code>&gt;&gt;&gt; err.spec\n#xyz()\n&gt;&gt;&gt; err.message\n'an error'\n</code></pre> <p>And finally, instances can of course be serialized and encoded:</p> <pre><code>&gt;&gt;&gt; print(stringify(err))\n&lt;stream-listener-error &lt;xyz&gt; \"an error\"&gt;\n&gt;&gt;&gt; canonicalize(err)\nb'\\xb4\\xb3\\x15stream-listener-error\\xb4\\xb3\\x03xyz\\x84\\xb1\\x08an error\\x84'\n</code></pre>"},{"location":"schema/#preserves.schema--example-2-streammode-a-sum-type","title":"Example 2: stream.Mode, a sum type","text":"<p>Now let's consider the definition of Mode, which appears in the source as</p> <pre><code>Mode = =bytes / @lines LineMode / &lt;packet @size int&gt; / &lt;object @description any&gt; .\n</code></pre> <p>This reads, in the Preserves Schema language, as an alternation (disjoint union, variant, sum type) of four possible kinds of value: the symbol <code>bytes</code>; a <code>LineMode</code> value; a record with <code>packet</code> as its label and an integer as its only field; or a record with <code>object</code> as its label and any kind of value as its only field. In Python, this becomes:</p> <pre><code>&gt;&gt;&gt; bundle.stream.Mode.bytes\n&lt;class 'stream.Mode.bytes'&gt;\n&gt;&gt;&gt; bundle.stream.Mode.lines\n&lt;class 'stream.Mode.lines'&gt;\n&gt;&gt;&gt; bundle.stream.Mode.packet\n&lt;class 'stream.Mode.packet'&gt;\n&gt;&gt;&gt; bundle.stream.Mode.object\n&lt;class 'stream.Mode.object'&gt;\n</code></pre> <p>As before, <code>Mode</code> includes a decode method that analyzes an input value:</p> <pre><code>&gt;&gt;&gt; bundle.stream.Mode.decode(parse('bytes'))\nMode.bytes()\n&gt;&gt;&gt; bundle.stream.Mode.decode(parse('lf'))\nMode.lines(LineMode.lf())\n&gt;&gt;&gt; bundle.stream.Mode.decode(parse('&lt;packet 123&gt;'))\nMode.packet {'size': 123}\n&gt;&gt;&gt; bundle.stream.Mode.decode(parse('&lt;object \"?\"&gt;'))\nMode.object {'description': '?'}\n</code></pre> <p>Invalid input causes SchemaDecodeFailed to be raised:</p> <pre><code>&gt;&gt;&gt; bundle.stream.Mode.decode(parse('&lt;i-am-not-a-valid-mode&gt;'))\nTraceback (most recent call last):\n ...\npreserves.schema.SchemaDecodeFailed: Could not decode &lt;i-am-not-a-valid-mode&gt; using &lt;class 'stream.Mode'&gt;\nMost likely reason: in stream.LineMode.crlf: &lt;lit crlf&gt; didn't match &lt;i-am-not-a-valid-mode&gt;\nFull explanation: \n in stream.Mode: matching &lt;i-am-not-a-valid-mode&gt;\n in stream.Mode.bytes: &lt;lit bytes&gt; didn't match &lt;i-am-not-a-valid-mode&gt;\n in stream.Mode.lines: &lt;ref [] LineMode&gt; didn't match &lt;i-am-not-a-valid-mode&gt;\n in stream.LineMode: matching &lt;i-am-not-a-valid-mode&gt;\n in stream.LineMode.lf: &lt;lit lf&gt; didn't match &lt;i-am-not-a-valid-mode&gt;\n in stream.LineMode.crlf: &lt;lit crlf&gt; didn't match &lt;i-am-not-a-valid-mode&gt;\n in stream.Mode.packet: &lt;lit packet&gt; didn't match i-am-not-a-valid-mode\n in stream.Mode.object: &lt;lit object&gt; didn't match i-am-not-a-valid-mode\n</code></pre> <p>The \"full explanation\" includes details on which parses were attempted, and why they failed.</p> <p>Again, the try_decode method catches SchemaDecodeFailed, transforming it into <code>None</code>:</p> <pre><code>&gt;&gt;&gt; bundle.stream.Mode.try_decode(parse('bytes'))\nMode.bytes()\n&gt;&gt;&gt; bundle.stream.Mode.try_decode(parse('&lt;i-am-not-a-valid-mode&gt;'))\n</code></pre> <p>Direct instantiation is done with the variant classes, not with <code>Mode</code> itself:</p> <pre><code>&gt;&gt;&gt; bundle.stream.Mode.bytes()\nMode.bytes()\n&gt;&gt;&gt; bundle.stream.Mode.lines(bundle.stream.LineMode.lf())\nMode.lines(LineMode.lf())\n&gt;&gt;&gt; bundle.stream.Mode.packet(123)\nMode.packet {'size': 123}\n&gt;&gt;&gt; bundle.stream.Mode.object('?')\nMode.object {'description': '?'}\n</code></pre> <p>Fields and contents can be queried as usual:</p> <pre><code>&gt;&gt;&gt; bundle.stream.Mode.lines(bundle.stream.LineMode.lf()).value\nLineMode.lf()\n&gt;&gt;&gt; bundle.stream.Mode.packet(123).size\n123\n&gt;&gt;&gt; bundle.stream.Mode.object('?').description\n'?'\n</code></pre> <p>And serialization and encoding are also as expected:</p> <pre><code>&gt;&gt;&gt; print(stringify(bundle.stream.Mode.bytes()))\nbytes\n&gt;&gt;&gt; print(stringify(bundle.stream.Mode.lines(bundle.stream.LineMode.lf())))\nlf\n&gt;&gt;&gt; print(stringify(bundle.stream.Mode.packet(123)))\n&lt;packet 123&gt;\n&gt;&gt;&gt; print(stringify(bundle.stream.Mode.object('?')))\n&lt;object \"?\"&gt;\n&gt;&gt;&gt; canonicalize(bundle.stream.Mode.object('?'))\nb'\\xb4\\xb3\\x06object\\xb1\\x01?\\x84'\n</code></pre> <p>Finally, the VARIANT attribute of instances allows code to dispatch on what kind of data it is handling at a given moment:</p> <pre><code>&gt;&gt;&gt; bundle.stream.Mode.bytes().VARIANT\n#bytes\n&gt;&gt;&gt; bundle.stream.Mode.lines(bundle.stream.LineMode.lf()).VARIANT\n#lines\n&gt;&gt;&gt; bundle.stream.Mode.packet(123).VARIANT\n#packet\n&gt;&gt;&gt; bundle.stream.Mode.object('?').VARIANT\n#object\n</code></pre>"},{"location":"schema/#preserves.schema.meta","title":"<code>meta = load_schema_file(__metaschema_filename).schema</code> <code>module-attribute</code>","text":"<p>Schema module Namespace corresponding to Preserves Schema's metaschema.</p>"},{"location":"schema/#preserves.schema.Compiler","title":"<code>Compiler()</code>","text":"<p>Instances of Compiler populate an initially-empty Namespace by loading and compiling schema bundle files.</p> <pre><code>&gt;&gt;&gt; c = Compiler()\n&gt;&gt;&gt; c.load('docs/syndicate-protocols-schema-bundle.bin')\n&gt;&gt;&gt; type(c.root)\n&lt;class 'preserves.schema.Namespace'&gt;\n</code></pre> <p>Attributes:</p> Name Type Description <code>root</code> <code>Namespace</code> <p>the root namespace into which top-level schema modules are installed.</p> Source code in <code>preserves/schema.py</code> <pre><code>def __init__(self):\n self.root = Namespace(())\n</code></pre>"},{"location":"schema/#preserves.schema.Compiler.load","title":"<code>load(filename)</code>","text":"<p>Opens the file at <code>filename</code>, passing the resulting file object to load_filelike.</p> Source code in <code>preserves/schema.py</code> <pre><code>def load(self, filename):\n \"\"\"Opens the file at `filename`, passing the resulting file object to\n [load_filelike][preserves.schema.Compiler.load_filelike].\"\"\"\n filename = pathlib.Path(filename)\n with open(filename, 'rb') as f:\n self.load_filelike(f, filename.stem)\n</code></pre>"},{"location":"schema/#preserves.schema.Compiler.load_filelike","title":"<code>load_filelike(f, module_name=None)</code>","text":"<p>Reads a <code>meta.Bundle</code> or <code>meta.Schema</code> from the filelike object <code>f</code>, compiling and installing it in <code>self.root</code>. If <code>f</code> contains a bundle, <code>module_name</code> is not used, since the schema modules in the bundle know their own names; if <code>f</code> contains a plain schema module, however, <code>module_name</code> is used directly if it is a string, and if it is <code>None</code>, a suitable module name is computed from the <code>name</code> attribute of <code>f</code>, if it is present. If <code>name</code> is absent in that case, <code>ValueError</code> is raised.</p> Source code in <code>preserves/schema.py</code> <pre><code>def load_filelike(self, f, module_name=None):\n \"\"\"Reads a `meta.Bundle` or `meta.Schema` from the filelike object `f`, compiling and\n installing it in `self.root`. If `f` contains a bundle, `module_name` is not used,\n since the schema modules in the bundle know their own names; if `f` contains a plain\n schema module, however, `module_name` is used directly if it is a string, and if it is\n `None`, a suitable module name is computed from the `name` attribute of `f`, if it is\n present. If `name` is absent in that case, `ValueError` is raised.\n\n \"\"\"\n x = Decoder(f.read()).next()\n if x.key == SCHEMA:\n if module_name is None:\n if hasattr(f, 'name'):\n module_name = pathlib.Path(f.name).stem\n else:\n raise ValueError('Cannot load schema module from filelike object without a module_name')\n self.load_schema((Symbol(module_name),), x)\n elif x.key == BUNDLE:\n for (p, s) in x[0].items():\n self.load_schema(p, s)\n</code></pre>"},{"location":"schema/#preserves.schema.Definition","title":"<code>Definition(*args, **kwargs)</code>","text":"<p> Bases: <code>SchemaObject</code></p> <p>Subclasses of Definition are used to represent both standalone non-alternation definitions as well as alternatives within an Enumeration.</p> <pre><code>&gt;&gt;&gt; bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')\n\n&gt;&gt;&gt; bundle.stream.StreamListenerError.FIELD_NAMES\n['spec', 'message']\n&gt;&gt;&gt; bundle.stream.StreamListenerError.SAFE_FIELD_NAMES\n['spec', 'message']\n&gt;&gt;&gt; bundle.stream.StreamListenerError.ENUMERATION is None\nTrue\n\n&gt;&gt;&gt; bundle.stream.Mode.object.FIELD_NAMES\n['description']\n&gt;&gt;&gt; bundle.stream.Mode.object.SAFE_FIELD_NAMES\n['description']\n&gt;&gt;&gt; bundle.stream.Mode.object.ENUMERATION is bundle.stream.Mode\nTrue\n\n&gt;&gt;&gt; bundle.stream.CreditAmount.count.FIELD_NAMES\n[]\n&gt;&gt;&gt; bundle.stream.CreditAmount.count.SAFE_FIELD_NAMES\n[]\n&gt;&gt;&gt; bundle.stream.CreditAmount.count.ENUMERATION is bundle.stream.CreditAmount\nTrue\n\n&gt;&gt;&gt; bundle.stream.CreditAmount.decode(parse('123'))\nCreditAmount.count(123)\n&gt;&gt;&gt; bundle.stream.CreditAmount.count(123)\nCreditAmount.count(123)\n&gt;&gt;&gt; bundle.stream.CreditAmount.count(123).value\n123\n</code></pre> Source code in <code>preserves/schema.py</code> <pre><code>def __init__(self, *args, **kwargs):\n self._fields = args\n if self.SIMPLE:\n if self.EMPTY:\n if len(args) != 0:\n raise TypeError('%s takes no arguments' % (self._constructor_name(),))\n else:\n if len(args) != 1:\n raise TypeError('%s needs exactly one argument' % (self._constructor_name(),))\n self.value = args[0]\n else:\n i = 0\n for arg in args:\n if i &gt;= len(self.FIELD_NAMES):\n raise TypeError('%s given too many positional arguments' % (self._constructor_name(),))\n setattr(self, self.SAFE_FIELD_NAMES[i], arg)\n i = i + 1\n for (argname, arg) in kwargs.items():\n if hasattr(self, argname):\n raise TypeError('%s given duplicate attribute: %r' % (self._constructor_name, argname))\n if argname not in self.SAFE_FIELD_NAMES:\n raise TypeError('%s given unknown attribute: %r' % (self._constructor_name, argname))\n setattr(self, argname, arg)\n i = i + 1\n if i != len(self.FIELD_NAMES):\n raise TypeError('%s needs argument(s) %r' % (self._constructor_name(), self.FIELD_NAMES))\n</code></pre>"},{"location":"schema/#preserves.schema.Definition.ENUMERATION","title":"<code>ENUMERATION = None</code> <code>class-attribute</code> <code>instance-attribute</code>","text":"<p><code>None</code> for standalone top-level definitions with a module; otherwise, an Enumeration subclass representing a top-level alternation definition.</p>"},{"location":"schema/#preserves.schema.Definition.FIELD_NAMES","title":"<code>FIELD_NAMES = []</code> <code>class-attribute</code> <code>instance-attribute</code>","text":"<p>List of strings: names of the fields contained within this definition, if it has named fields at all; otherwise, an empty list, and the definition is a simple wrapper for another value, in which case that value is accessed via the <code>value</code> attribute.</p>"},{"location":"schema/#preserves.schema.Definition.SAFE_FIELD_NAMES","title":"<code>SAFE_FIELD_NAMES = []</code> <code>class-attribute</code> <code>instance-attribute</code>","text":"<p>The list produced by mapping safeattrname over FIELD_NAMES.</p>"},{"location":"schema/#preserves.schema.Enumeration","title":"<code>Enumeration()</code>","text":"<p> Bases: <code>SchemaObject</code></p> <p>Subclasses of Enumeration represent a group of variant options within a sum type.</p> <pre><code>&gt;&gt;&gt; bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')\n\n&gt;&gt;&gt; import pprint\n&gt;&gt;&gt; pprint.pprint(bundle.stream.Mode.VARIANTS)\n[(#bytes, &lt;class 'stream.Mode.bytes'&gt;),\n (#lines, &lt;class 'stream.Mode.lines'&gt;),\n (#packet, &lt;class 'stream.Mode.packet'&gt;),\n (#object, &lt;class 'stream.Mode.object'&gt;)]\n\n&gt;&gt;&gt; bundle.stream.Mode.VARIANTS[0][1] is bundle.stream.Mode.bytes\nTrue\n</code></pre> Source code in <code>preserves/schema.py</code> <pre><code>def __init__(self):\n raise TypeError('Cannot create instance of Enumeration')\n</code></pre>"},{"location":"schema/#preserves.schema.Enumeration.VARIANTS","title":"<code>VARIANTS = None</code> <code>class-attribute</code> <code>instance-attribute</code>","text":"<p>List of <code>(Symbol, SchemaObject class)</code> tuples representing the possible options within this sum type.</p>"},{"location":"schema/#preserves.schema.Namespace","title":"<code>Namespace(prefix)</code>","text":"<p>A Namespace is a dictionary-like object representing a schema module that knows its location in a schema module hierarchy and whose attributes correspond to definitions and submodules within the schema module.</p> <p>Attributes:</p> Name Type Description <code>_prefix</code> <code>tuple[Symbol]</code> <p>path to this module/Namespace from the root Namespace</p> Source code in <code>preserves/schema.py</code> <pre><code>def __init__(self, prefix):\n self._prefix = prefix\n</code></pre>"},{"location":"schema/#preserves.schema.SchemaDecodeFailed","title":"<code>SchemaDecodeFailed(cls, p, v, failures=None)</code>","text":"<p> Bases: <code>ValueError</code></p> <p>Raised when decode cannot find a way to parse a given input.</p> <p>Attributes:</p> Name Type Description <code>cls</code> <code>class</code> <p>the SchemaObject subclass attempting the parse</p> <code>pattern</code> <code>Value</code> <p>the failing pattern, a <code>Value</code> conforming to schema <code>meta.Pattern</code></p> <code>value</code> <code>Value</code> <p>the unparseable value</p> <code>failures</code> <code>list[SchemaDecodeFailed]</code> <p>descriptions of failed paths attempted during the match this failure describes</p> Source code in <code>preserves/schema.py</code> <pre><code>def __init__(self, cls, p, v, failures=None):\n super().__init__()\n self.cls = cls\n self.pattern = p\n self.value = v\n self.failures = [] if failures is None else failures\n</code></pre>"},{"location":"schema/#preserves.schema.SchemaObject","title":"<code>SchemaObject</code>","text":"<p>Base class for classes representing grammatical productions in a schema: instances of SchemaObject represent schema definitions. This is an abstract class, as are its subclasses Enumeration and Definition. It is subclasses of those subclasses, automatically produced during schema loading, that are actually instantiated.</p> <pre><code>&gt;&gt;&gt; bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')\n\n&gt;&gt;&gt; bundle.stream.Mode.mro()[1:-1]\n[&lt;class 'preserves.schema.Enumeration'&gt;, &lt;class 'preserves.schema.SchemaObject'&gt;]\n\n&gt;&gt;&gt; bundle.stream.Mode.packet.mro()[1:-1]\n[&lt;class 'stream.Mode._ALL'&gt;, &lt;class 'preserves.schema.Definition'&gt;, &lt;class 'preserves.schema.SchemaObject'&gt;]\n\n&gt;&gt;&gt; bundle.stream.StreamListenerError.mro()[1:-1]\n[&lt;class 'preserves.schema.Definition'&gt;, &lt;class 'preserves.schema.SchemaObject'&gt;]\n</code></pre> <p>Illustrating the class attributes on SchemaObject subclasses:</p> <pre><code>&gt;&gt;&gt; bundle.stream.Mode.ROOTNS is bundle\nTrue\n\n&gt;&gt;&gt; print(stringify(bundle.stream.Mode.SCHEMA, indent=2))\n&lt;or [\n [\n \"bytes\"\n &lt;lit bytes&gt;\n ]\n [\n \"lines\"\n &lt;ref [] LineMode&gt;\n ]\n [\n \"packet\"\n &lt;rec &lt;lit packet&gt; &lt;tuple [&lt;named size &lt;atom SignedInteger&gt;&gt;]&gt;&gt;\n ]\n [\n \"object\"\n &lt;rec &lt;lit object&gt; &lt;tuple [&lt;named description any&gt;]&gt;&gt;\n ]\n]&gt;\n\n&gt;&gt;&gt; bundle.stream.Mode.MODULE_PATH\n(#stream,)\n\n&gt;&gt;&gt; bundle.stream.Mode.NAME\n#Mode\n\n&gt;&gt;&gt; bundle.stream.Mode.VARIANT is None\nTrue\n&gt;&gt;&gt; bundle.stream.Mode.packet.VARIANT\n#packet\n</code></pre>"},{"location":"schema/#preserves.schema.SchemaObject.MODULE_PATH","title":"<code>MODULE_PATH = None</code> <code>class-attribute</code> <code>instance-attribute</code>","text":"<p>A sequence (tuple) of Symbols naming the path from the root to the schema module containing this definition.</p>"},{"location":"schema/#preserves.schema.SchemaObject.NAME","title":"<code>NAME = None</code> <code>class-attribute</code> <code>instance-attribute</code>","text":"<p>A Symbol naming this definition within its module.</p>"},{"location":"schema/#preserves.schema.SchemaObject.ROOTNS","title":"<code>ROOTNS = None</code> <code>class-attribute</code> <code>instance-attribute</code>","text":"<p>A Namespace that is the top-level environment for all bundles included in the Compiler run that produced this SchemaObject.</p>"},{"location":"schema/#preserves.schema.SchemaObject.SCHEMA","title":"<code>SCHEMA = None</code> <code>class-attribute</code> <code>instance-attribute</code>","text":"<p>A <code>Value</code> conforming to schema <code>meta.Definition</code> (and thus often to <code>meta.Pattern</code> etc.), interpreted by the SchemaObject machinery to drive parsing, unparsing and so forth.</p>"},{"location":"schema/#preserves.schema.SchemaObject.VARIANT","title":"<code>VARIANT = None</code> <code>class-attribute</code> <code>instance-attribute</code>","text":"<p><code>None</code> for Definitions (such as <code>bundle.stream.StreamListenerError</code> above) and for overall Enumerations (such as <code>bundle.stream.Mode</code>), or a Symbol for variant definitions contained within an enumeration (such as <code>bundle.stream.Mode.packet</code>).</p>"},{"location":"schema/#preserves.schema.SchemaObject.__preserve__","title":"<code>__preserve__()</code>","text":"<p>Called by preserves.values.preserve: unparses the information represented by this instance, using its schema definition, to produce a Preserves <code>Value</code>.</p> Source code in <code>preserves/schema.py</code> <pre><code>def __preserve__(self):\n \"\"\"Called by [preserves.values.preserve][]: *unparses* the information represented by\n this instance, using its schema definition, to produce a Preserves `Value`.\"\"\"\n raise NotImplementedError('Subclass responsibility')\n</code></pre>"},{"location":"schema/#preserves.schema.SchemaObject.decode","title":"<code>decode(v)</code> <code>classmethod</code>","text":"<p>Parses <code>v</code> using the SCHEMA, returning a (sub)instance of SchemaObject or raising SchemaDecodeFailed.</p> Source code in <code>preserves/schema.py</code> <pre><code>@classmethod\ndef decode(cls, v):\n \"\"\"Parses `v` using the [SCHEMA][preserves.schema.SchemaObject.SCHEMA], returning a\n (sub)instance of [SchemaObject][preserves.schema.SchemaObject] or raising\n [SchemaDecodeFailed][preserves.schema.SchemaDecodeFailed].\"\"\"\n raise NotImplementedError('Subclass responsibility')\n</code></pre>"},{"location":"schema/#preserves.schema.SchemaObject.try_decode","title":"<code>try_decode(v)</code> <code>classmethod</code>","text":"<p>Parses <code>v</code> using the SCHEMA, returning a (sub)instance of SchemaObject or <code>None</code> if parsing failed.</p> Source code in <code>preserves/schema.py</code> <pre><code>@classmethod\ndef try_decode(cls, v):\n \"\"\"Parses `v` using the [SCHEMA][preserves.schema.SchemaObject.SCHEMA], returning a\n (sub)instance of [SchemaObject][preserves.schema.SchemaObject] or `None` if parsing\n failed.\"\"\"\n try:\n return cls.decode(v)\n except SchemaDecodeFailed:\n return None\n</code></pre>"},{"location":"schema/#preserves.schema.extend","title":"<code>extend(cls)</code>","text":"<p>A decorator for function definitions. Useful for adding behaviour to the classes resulting from loading a schema module:</p> <pre><code>&gt;&gt;&gt; bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')\n\n&gt;&gt;&gt; @extend(bundle.stream.LineMode.lf)\n... def what_am_i(self):\n... return 'I am a LINEFEED linemode'\n\n&gt;&gt;&gt; @extend(bundle.stream.LineMode.crlf)\n... def what_am_i(self):\n... return 'I am a CARRIAGE-RETURN-PLUS-LINEFEED linemode'\n\n&gt;&gt;&gt; bundle.stream.LineMode.lf()\nLineMode.lf()\n&gt;&gt;&gt; bundle.stream.LineMode.lf().what_am_i()\n'I am a LINEFEED linemode'\n\n&gt;&gt;&gt; bundle.stream.LineMode.crlf()\nLineMode.crlf()\n&gt;&gt;&gt; bundle.stream.LineMode.crlf().what_am_i()\n'I am a CARRIAGE-RETURN-PLUS-LINEFEED linemode'\n</code></pre> Source code in <code>preserves/schema.py</code> <pre><code>def extend(cls):\n \"\"\"A decorator for function definitions. Useful for adding *behaviour* to the classes\n resulting from loading a schema module:\n\n ```python\n &gt;&gt;&gt; bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')\n\n &gt;&gt;&gt; @extend(bundle.stream.LineMode.lf)\n ... def what_am_i(self):\n ... return 'I am a LINEFEED linemode'\n\n &gt;&gt;&gt; @extend(bundle.stream.LineMode.crlf)\n ... def what_am_i(self):\n ... return 'I am a CARRIAGE-RETURN-PLUS-LINEFEED linemode'\n\n &gt;&gt;&gt; bundle.stream.LineMode.lf()\n LineMode.lf()\n &gt;&gt;&gt; bundle.stream.LineMode.lf().what_am_i()\n 'I am a LINEFEED linemode'\n\n &gt;&gt;&gt; bundle.stream.LineMode.crlf()\n LineMode.crlf()\n &gt;&gt;&gt; bundle.stream.LineMode.crlf().what_am_i()\n 'I am a CARRIAGE-RETURN-PLUS-LINEFEED linemode'\n\n ```\n\n \"\"\"\n @wraps(cls)\n def extender(f):\n setattr(cls, f.__name__, f)\n return f\n return extender\n</code></pre>"},{"location":"schema/#preserves.schema.load_schema_file","title":"<code>load_schema_file(filename)</code>","text":"<p>Simple entry point to the compiler: creates a Compiler, calls load on it, and returns its <code>root</code> Namespace.</p> <pre><code>&gt;&gt;&gt; bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')\n&gt;&gt;&gt; type(bundle)\n&lt;class 'preserves.schema.Namespace'&gt;\n</code></pre> Source code in <code>preserves/schema.py</code> <pre><code>def load_schema_file(filename):\n \"\"\"Simple entry point to the compiler: creates a [Compiler][preserves.schema.Compiler],\n calls [load][preserves.schema.Compiler.load] on it, and returns its `root`\n [Namespace][preserves.schema.Namespace].\n\n ```python\n &gt;&gt;&gt; bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')\n &gt;&gt;&gt; type(bundle)\n &lt;class 'preserves.schema.Namespace'&gt;\n\n ```\n \"\"\"\n c = Compiler()\n c.load(filename)\n return c.root\n</code></pre>"},{"location":"schema/#preserves.schema.safeattrname","title":"<code>safeattrname(k)</code>","text":"<p>Escapes Python keywords by prepending <code>_</code>; passes all other strings through.</p> Source code in <code>preserves/schema.py</code> <pre><code>def safeattrname(k):\n \"\"\"Escapes Python keywords by prepending `_`; passes all other strings through.\"\"\"\n return k + '_' if keyword.iskeyword(k) else k\n</code></pre>"},{"location":"text/","title":"Human-readable text syntax","text":"<p>The preserves.text module implements the Preserves human-readable text syntax.</p> <p>The main entry points are functions stringify, parse, and parse_with_annotations.</p> <pre><code>&gt;&gt;&gt; stringify(Record(Symbol('hi'), [1, [2, 3]]))\n'&lt;hi 1 [2 3]&gt;'\n&gt;&gt;&gt; parse('&lt;hi 1 [2 3]&gt;')\n#hi(1, (2, 3))\n</code></pre>"},{"location":"text/#preserves.text.Formatter","title":"<code>Formatter(format_embedded=lambda : x, indent=None, with_commas=False, trailing_comma=False, include_annotations=True)</code>","text":"<p> Bases: <code>TextCodec</code></p> <p>Printer (and indenting pretty-printer) for producing human-readable syntax from Preserves <code>Value</code>s.</p> <pre><code>&gt;&gt;&gt; f = Formatter()\n&gt;&gt;&gt; f.append({'a': 1, 'b': 2})\n&gt;&gt;&gt; f.append(Record(Symbol('label'), ['field1', ['field2item1', 'field2item2']]))\n&gt;&gt;&gt; print(f.contents())\n{\"a\": 1 \"b\": 2} &lt;label \"field1\" [\"field2item1\" \"field2item2\"]&gt;\n\n&gt;&gt;&gt; f = Formatter(indent=4)\n&gt;&gt;&gt; f.append({'a': 1, 'b': 2})\n&gt;&gt;&gt; f.append(Record(Symbol('label'), ['field1', ['field2item1', 'field2item2']]))\n&gt;&gt;&gt; print(f.contents())\n{\n \"a\": 1\n \"b\": 2\n}\n&lt;label \"field1\" [\n \"field2item1\"\n \"field2item2\"\n]&gt;\n</code></pre> <p>Parameters:</p> Name Type Description Default <code>format_embedded</code> <p>function accepting an Embedded.embeddedValue and returning a <code>Value</code> for serialization.</p> <code>lambda : x</code> <code>indent</code> <code>int | None</code> <p><code>None</code> disables indented pretty-printing; otherwise, an <code>int</code> specifies indentation per nesting-level.</p> <code>None</code> <code>with_commas</code> <code>bool</code> <p><code>True</code> causes commas to separate sequence and set items and dictionary entries; <code>False</code> omits commas.</p> <code>False</code> <code>trailing_comma</code> <code>bool</code> <p><code>True</code> causes a comma to be printed after the final item or entry in a sequence, set or dictionary; <code>False</code> omits this trailing comma</p> <code>False</code> <code>include_annotations</code> <code>bool</code> <p><code>True</code> causes annotations to be included in the output; <code>False</code> causes them to be omitted.</p> <code>True</code> <p>Attributes:</p> Name Type Description <code>indent_delta</code> <code>int</code> <p>indentation per nesting-level</p> <code>chunks</code> <code>list[str]</code> <p>fragments of output</p> Source code in <code>preserves/text.py</code> <pre><code>def __init__(self,\n format_embedded=lambda x: x,\n indent=None,\n with_commas=False,\n trailing_comma=False,\n include_annotations=True):\n super(Formatter, self).__init__()\n self.indent_delta = 0 if indent is None else indent\n self.indent_distance = 0\n self.nesting = 0\n self.with_commas = with_commas\n self.trailing_comma = trailing_comma\n self.chunks = []\n self._format_embedded = format_embedded\n self.include_annotations = include_annotations\n</code></pre>"},{"location":"text/#preserves.text.Formatter.append","title":"<code>append(v)</code>","text":"<p>Extend <code>self.chunks</code> with at least one chunk, together making up the text representation of <code>v</code>.</p> Source code in <code>preserves/text.py</code> <pre><code>def append(self, v):\n \"\"\"Extend `self.chunks` with at least one chunk, together making up the text\n representation of `v`.\"\"\"\n if self.chunks and self.nesting == 0:\n self.write_indent_space()\n try:\n self.nesting += 1\n self._append(v)\n finally:\n self.nesting -= 1\n</code></pre>"},{"location":"text/#preserves.text.Formatter.contents","title":"<code>contents()</code>","text":"<p>Returns a <code>str</code> constructed from the join of the chunks in <code>self.chunks</code>.</p> Source code in <code>preserves/text.py</code> <pre><code>def contents(self):\n \"\"\"Returns a `str` constructed from the join of the chunks in `self.chunks`.\"\"\"\n return u''.join(self.chunks)\n</code></pre>"},{"location":"text/#preserves.text.Formatter.is_indenting","title":"<code>is_indenting()</code>","text":"<p>Returns <code>True</code> iff this Formatter is in pretty-printing indenting mode.</p> Source code in <code>preserves/text.py</code> <pre><code>def is_indenting(self):\n \"\"\"Returns `True` iff this [Formatter][preserves.text.Formatter] is in pretty-printing\n indenting mode.\"\"\"\n return self.indent_delta &gt; 0\n</code></pre>"},{"location":"text/#preserves.text.Parser","title":"<code>Parser(input_buffer='', include_annotations=False, parse_embedded=lambda : x)</code>","text":"<p> Bases: <code>TextCodec</code></p> <p>Parser for the human-readable Preserves text syntax.</p> <p>Parameters:</p> Name Type Description Default <code>input_buffer</code> <code>str</code> <p>initial contents of the input buffer; may subsequently be extended by calling extend.</p> <code>''</code> <code>include_annotations</code> <code>bool</code> <p>if <code>True</code>, wrap each value and subvalue in an Annotated object.</p> <code>False</code> <code>parse_embedded</code> <p>function accepting a <code>Value</code> and returning a possibly-decoded form of that value suitable for placing into an Embedded object.</p> <code>lambda : x</code> <p>Normal usage is to supply input text, and keep calling next until a ShortPacket exception is raised:</p> <pre><code>&gt;&gt;&gt; d = Parser('123 \"hello\" @x []')\n&gt;&gt;&gt; d.next()\n123\n&gt;&gt;&gt; d.next()\n'hello'\n&gt;&gt;&gt; d.next()\n()\n&gt;&gt;&gt; d.next()\nTraceback (most recent call last):\n ...\npreserves.error.ShortPacket: Short input buffer\n</code></pre> <p>Alternatively, keep calling try_next until it yields <code>None</code>, which is not in the domain of Preserves <code>Value</code>s:</p> <pre><code>&gt;&gt;&gt; d = Parser('123 \"hello\" @x []')\n&gt;&gt;&gt; d.try_next()\n123\n&gt;&gt;&gt; d.try_next()\n'hello'\n&gt;&gt;&gt; d.try_next()\n()\n&gt;&gt;&gt; d.try_next()\n</code></pre> <p>For convenience, Parser implements the iterator interface, backing it with try_next, so you can simply iterate over all complete values in an input:</p> <pre><code>&gt;&gt;&gt; d = Parser('123 \"hello\" @x []')\n&gt;&gt;&gt; list(d)\n[123, 'hello', ()]\n</code></pre> <pre><code>&gt;&gt;&gt; for v in Parser('123 \"hello\" @x []'):\n... print(repr(v))\n123\n'hello'\n()\n</code></pre> <p>Supply <code>include_annotations=True</code> to read annotations alongside the annotated values:</p> <pre><code>&gt;&gt;&gt; d = Parser('123 \"hello\" @x []', include_annotations=True)\n&gt;&gt;&gt; list(d)\n[123, 'hello', @#x ()]\n</code></pre> <p>If you are incrementally reading from, say, a socket, you can use extend to add new input as if comes available:</p> <pre><code>&gt;&gt;&gt; d = Parser('123 \"he')\n&gt;&gt;&gt; d.try_next()\n123\n&gt;&gt;&gt; d.try_next() # returns None because the input is incomplete\n&gt;&gt;&gt; d.extend('llo\"')\n&gt;&gt;&gt; d.try_next()\n'hello'\n&gt;&gt;&gt; d.try_next()\n</code></pre> <p>Attributes:</p> Name Type Description <code>input_buffer</code> <code>str</code> <p>buffered input waiting to be processed</p> <code>index</code> <code>int</code> <p>read position within <code>input_buffer</code></p> Source code in <code>preserves/text.py</code> <pre><code>def __init__(self, input_buffer=u'', include_annotations=False, parse_embedded=lambda x: x):\n super(Parser, self).__init__()\n self.input_buffer = input_buffer\n self.index = 0\n self.include_annotations = include_annotations\n self.parse_embedded = parse_embedded\n</code></pre>"},{"location":"text/#preserves.text.Parser.extend","title":"<code>extend(text)</code>","text":"<p>Appends <code>text</code> to the remaining contents of <code>self.input_buffer</code>, trimming already-processed text from the front of <code>self.input_buffer</code> and resetting <code>self.index</code> to zero.</p> Source code in <code>preserves/text.py</code> <pre><code>def extend(self, text):\n \"\"\"Appends `text` to the remaining contents of `self.input_buffer`, trimming already-processed\n text from the front of `self.input_buffer` and resetting `self.index` to zero.\"\"\"\n self.input_buffer = self.input_buffer[self.index:] + text\n self.index = 0\n</code></pre>"},{"location":"text/#preserves.text.Parser.next","title":"<code>next()</code>","text":"<p>Reads the next complete <code>Value</code> from the internal buffer, raising ShortPacket if too few bytes are available, or DecodeError if the input is invalid somehow.</p> Source code in <code>preserves/text.py</code> <pre><code>def next(self):\n \"\"\"Reads the next complete `Value` from the internal buffer, raising\n [ShortPacket][preserves.error.ShortPacket] if too few bytes are available, or\n [DecodeError][preserves.error.DecodeError] if the input is invalid somehow.\n\n \"\"\"\n self.skip_whitespace()\n c = self.peek()\n if c == '\"':\n self.skip()\n return self.wrap(self.read_string('\"'))\n if c == '|':\n self.skip()\n return self.wrap(Symbol(self.read_string('|')))\n if c == '@':\n self.skip()\n return self.unshift_annotation(self.next(), self.next())\n if c == ';':\n raise DecodeError('Semicolon is reserved syntax')\n if c == ':':\n raise DecodeError('Unexpected key/value separator between items')\n if c == '#':\n self.skip()\n c = self.nextchar()\n if c in ' \\t': return self.unshift_annotation(self.comment_line(), self.next())\n if c in '\\n\\r': return self.unshift_annotation('', self.next())\n if c == 'f': self.require_delimiter('#f'); return self.wrap(False)\n if c == 't': self.require_delimiter('#t'); return self.wrap(True)\n if c == '{': return self.wrap(self.read_set())\n if c == '\"': return self.wrap(self.read_literal_binary())\n if c == 'x':\n c = self.nextchar()\n if c == '\"': return self.wrap(self.read_hex_binary())\n if c == 'd': return self.wrap(self.read_hex_float())\n raise DecodeError('Invalid #x syntax')\n if c == '[': return self.wrap(self.read_base64_binary())\n if c == '!':\n if self.parse_embedded is None:\n raise DecodeError('No parse_embedded function supplied')\n return self.wrap(Embedded(self.parse_embedded(self.next())))\n raise DecodeError('Invalid # syntax')\n if c == '&lt;':\n self.skip()\n vs = self.upto('&gt;', False)\n if len(vs) == 0:\n raise DecodeError('Missing record label')\n return self.wrap(Record(vs[0], vs[1:]))\n if c == '[':\n self.skip()\n return self.wrap(self.upto(']', True))\n if c == '{':\n self.skip()\n return self.wrap(self.read_dictionary())\n if c in '&gt;]},':\n raise DecodeError('Unexpected ' + c)\n self.skip()\n return self.wrap(self.read_raw_symbol_or_number([c]))\n</code></pre>"},{"location":"text/#preserves.text.Parser.try_next","title":"<code>try_next()</code>","text":"<p>Like next, but returns <code>None</code> instead of raising ShortPacket.</p> Source code in <code>preserves/text.py</code> <pre><code>def try_next(self):\n \"\"\"Like [next][preserves.text.Parser.next], but returns `None` instead of raising\n [ShortPacket][preserves.error.ShortPacket].\"\"\"\n start = self.index\n try:\n return self.next()\n except ShortPacket:\n self.index = start\n return None\n</code></pre>"},{"location":"text/#preserves.text.parse","title":"<code>parse(text, **kwargs)</code>","text":"<p>Yields the first complete encoded value from <code>text</code>, passing <code>kwargs</code> through to the Parser constructor. Raises exceptions as per next.</p> <p>Parameters:</p> Name Type Description Default <code>text</code> <code>str</code> <p>encoded data to decode</p> required Source code in <code>preserves/text.py</code> <pre><code>def parse(text, **kwargs):\n \"\"\"Yields the first complete encoded value from `text`, passing `kwargs` through to the\n [Parser][preserves.text.Parser] constructor. Raises exceptions as per\n [next][preserves.text.Parser.next].\n\n Args:\n text (str): encoded data to decode\n\n \"\"\"\n return Parser(input_buffer=text, **kwargs).next()\n</code></pre>"},{"location":"text/#preserves.text.parse_with_annotations","title":"<code>parse_with_annotations(bs, **kwargs)</code>","text":"<p>Like parse, but supplying <code>include_annotations=True</code> to the Parser constructor.</p> Source code in <code>preserves/text.py</code> <pre><code>def parse_with_annotations(bs, **kwargs):\n \"\"\"Like [parse][preserves.text.parse], but supplying `include_annotations=True` to the\n [Parser][preserves.text.Parser] constructor.\"\"\"\n return Parser(input_buffer=bs, include_annotations=True, **kwargs).next()\n</code></pre>"},{"location":"text/#preserves.text.stringify","title":"<code>stringify(v, **kwargs)</code>","text":"<p>Convert a single <code>Value</code> <code>v</code> to a string. Any supplied <code>kwargs</code> are passed on to the underlying Formatter constructor.</p> Source code in <code>preserves/text.py</code> <pre><code>def stringify(v, **kwargs):\n \"\"\"Convert a single `Value` `v` to a string. Any supplied `kwargs` are passed on to the\n underlying [Formatter][preserves.text.Formatter] constructor.\"\"\"\n e = Formatter(**kwargs)\n e.append(v)\n return e.contents()\n</code></pre>"},{"location":"values/","title":"Representations of Values","text":"<p>Python's strings, byte strings, integers, booleans, and double-precision floats stand directly for their Preserves counterparts. Wrapper objects for Symbol complete the suite of atomic types.</p> <p>Python's lists and tuples correspond to Preserves <code>Sequence</code>s, and dicts and sets to <code>Dictionary</code> and <code>Set</code> values, respectively. Preserves <code>Record</code>s are represented by Record objects. Finally, embedded values are represented by Embedded objects.</p> <p>The preserves.values module implements the core representations of Preserves <code>Value</code>s as Python values.</p>"},{"location":"values/#preserves.values.Annotated","title":"<code>Annotated(item)</code>","text":"<p> Bases: <code>object</code></p> <p>A Preserves <code>Value</code> along with a sequence of <code>Value</code>s annotating it. Compares equal to the underlying <code>Value</code>, ignoring the annotations. See the specification document for more about annotations.</p> <pre><code>&gt;&gt;&gt; import preserves\n&gt;&gt;&gt; a = preserves.parse('''\n... # A comment\n... [1 2 3]\n... ''', include_annotations=True)\n&gt;&gt;&gt; a\n@'A comment' (1, 2, 3)\n&gt;&gt;&gt; a.item\n(1, 2, 3)\n&gt;&gt;&gt; a.annotations\n['A comment']\n&gt;&gt;&gt; a == (1, 2, 3)\nTrue\n&gt;&gt;&gt; a == preserves.parse('@xyz [1 2 3]', include_annotations=True)\nTrue\n&gt;&gt;&gt; a[0]\nTraceback (most recent call last):\n ...\nTypeError: 'Annotated' object is not subscriptable\n&gt;&gt;&gt; a.item[0]\n1\n&gt;&gt;&gt; type(a.item[0])\n&lt;class 'preserves.values.Annotated'&gt;\n&gt;&gt;&gt; a.item[0].annotations\n[]\n&gt;&gt;&gt; print(preserves.stringify(a))\n@\"A comment\" [1 2 3]\n&gt;&gt;&gt; print(preserves.stringify(a, include_annotations=False))\n[1 2 3]\n</code></pre> <p>Attributes:</p> Name Type Description <code>item</code> <code>Value</code> <p>the underlying annotated <code>Value</code></p> <code>annotations</code> <code>list[Value]</code> <p>the annotations attached to <code>self.item</code></p> Source code in <code>preserves/values.py</code> <pre><code>def __init__(self, item):\n self.annotations = []\n self.item = item\n</code></pre>"},{"location":"values/#preserves.values.Annotated.peel","title":"<code>peel()</code>","text":"<p>Calls strip_annotations on <code>self</code> with <code>depth=1</code>.</p> Source code in <code>preserves/values.py</code> <pre><code>def peel(self):\n \"\"\"Calls [strip_annotations][preserves.values.strip_annotations] on `self` with `depth=1`.\"\"\"\n return strip_annotations(self, 1)\n</code></pre>"},{"location":"values/#preserves.values.Annotated.strip","title":"<code>strip(depth=inf)</code>","text":"<p>Calls strip_annotations on <code>self</code> and <code>depth</code>.</p> Source code in <code>preserves/values.py</code> <pre><code>def strip(self, depth=inf):\n \"\"\"Calls [strip_annotations][preserves.values.strip_annotations] on `self` and `depth`.\"\"\"\n return strip_annotations(self, depth)\n</code></pre>"},{"location":"values/#preserves.values.Embedded","title":"<code>Embedded(embeddedValue)</code>","text":"<p>Representation of a Preserves <code>Embedded</code> value. For more on the meaning and use of embedded values, see the specification.</p> <pre><code>&gt;&gt;&gt; import io\n&gt;&gt;&gt; e = Embedded(io.StringIO('some text'))\n&gt;&gt;&gt; e # doctest: +ELLIPSIS\n#!&lt;_io.StringIO object at ...&gt;\n&gt;&gt;&gt; e.embeddedValue # doctest: +ELLIPSIS\n&lt;_io.StringIO object at ...&gt;\n</code></pre> <pre><code>&gt;&gt;&gt; import preserves\n&gt;&gt;&gt; print(preserves.stringify(Embedded(None)))\nTraceback (most recent call last):\n ...\nTypeError: Cannot preserves-format: None\n&gt;&gt;&gt; print(preserves.stringify(Embedded(None), format_embedded=lambda x: 'abcdef'))\n#!\"abcdef\"\n</code></pre> <p>Attributes:</p> Name Type Description <code>embeddedValue</code> <p>any Python value; could be a platform object, could be a representation of a Preserves <code>Value</code>, could be <code>None</code>, could be anything!</p> Source code in <code>preserves/values.py</code> <pre><code>def __init__(self, embeddedValue):\n self.embeddedValue = embeddedValue\n</code></pre>"},{"location":"values/#preserves.values.ImmutableDict","title":"<code>ImmutableDict(*args, **kwargs)</code>","text":"<p> Bases: <code>dict</code></p> <p>A subclass of Python's built-in <code>dict</code> that overrides methods that could mutate the dictionary, causing them to raise <code>TypeError('Immutable')</code> if called.</p> <p>Implements the <code>__hash__</code> method, allowing ImmutableDict instances to be used whereever immutable data are permitted; in particular, as keys in other dictionaries.</p> <pre><code>&gt;&gt;&gt; d = ImmutableDict([('a', 1), ('b', 2)])\n&gt;&gt;&gt; d\n{'a': 1, 'b': 2}\n&gt;&gt;&gt; d['c'] = 3\nTraceback (most recent call last):\n ...\nTypeError: Immutable\n&gt;&gt;&gt; del d['b']\nTraceback (most recent call last):\n ...\nTypeError: Immutable\n</code></pre> Source code in <code>preserves/values.py</code> <pre><code>def __init__(self, *args, **kwargs):\n if hasattr(self, '__hash'): raise TypeError('Immutable')\n super(ImmutableDict, self).__init__(*args, **kwargs)\n self.__hash = None\n</code></pre>"},{"location":"values/#preserves.values.ImmutableDict.from_kvs","title":"<code>from_kvs(kvs)</code> <code>staticmethod</code>","text":"<p>Constructs an ImmutableDict from a sequence of alternating keys and values; compare to the ImmutableDict constructor, which takes a sequence of key-value pairs.</p> <pre><code>&gt;&gt;&gt; ImmutableDict.from_kvs(['a', 1, 'b', 2])\n{'a': 1, 'b': 2}\n&gt;&gt;&gt; ImmutableDict.from_kvs(['a', 1, 'b', 2])['c'] = 3\nTraceback (most recent call last):\n ...\nTypeError: Immutable\n</code></pre> Source code in <code>preserves/values.py</code> <pre><code>@staticmethod\ndef from_kvs(kvs):\n \"\"\"Constructs an [ImmutableDict][preserves.values.ImmutableDict] from a sequence of\n alternating keys and values; compare to the\n [ImmutableDict][preserves.values.ImmutableDict] constructor, which takes a sequence of\n key-value pairs.\n\n ```python\n &gt;&gt;&gt; ImmutableDict.from_kvs(['a', 1, 'b', 2])\n {'a': 1, 'b': 2}\n &gt;&gt;&gt; ImmutableDict.from_kvs(['a', 1, 'b', 2])['c'] = 3\n Traceback (most recent call last):\n ...\n TypeError: Immutable\n\n ```\n\n \"\"\"\n\n i = iter(kvs)\n result = ImmutableDict()\n result_proxy = super(ImmutableDict, result)\n try:\n while True:\n k = next(i)\n try:\n v = next(i)\n except StopIteration:\n raise DecodeError(\"Missing dictionary value\")\n if k in result:\n raise DecodeError(\"Duplicate key: \" + repr(k))\n result_proxy.__setitem__(k, v)\n except StopIteration:\n pass\n return result\n</code></pre>"},{"location":"values/#preserves.values.Record","title":"<code>Record(key, fields)</code>","text":"<p> Bases: <code>object</code></p> <p>Representation of Preserves <code>Record</code>s, which are a pair of a label <code>Value</code> and a sequence of field <code>Value</code>s.</p> <pre><code>&gt;&gt;&gt; r = Record(Symbol('label'), ['field1', ['field2item1', 'field2item2']])\n&gt;&gt;&gt; r\n#label('field1', ['field2item1', 'field2item2'])\n&gt;&gt;&gt; r.key\n#label\n&gt;&gt;&gt; r.fields\n('field1', ['field2item1', 'field2item2'])\n&gt;&gt;&gt; import preserves\n&gt;&gt;&gt; preserves.stringify(r)\n'&lt;label \"field1\" [\"field2item1\" \"field2item2\"]&gt;'\n&gt;&gt;&gt; r == preserves.parse('&lt;label \"field1\" [\"field2item1\" \"field2item2\"]&gt;')\nTrue\n</code></pre> <p>Parameters:</p> Name Type Description Default <code>key</code> <code>Value</code> <p>the <code>Record</code>'s label</p> required <code>fields</code> <code>iterable[Value]</code> <p>the fields of the <code>Record</code></p> required <p>Attributes:</p> Name Type Description <code>key</code> <code>Value</code> <p>the <code>Record</code>'s label</p> <code>fields</code> <code>tuple[Value]</code> <p>the fields of the <code>Record</code></p> Source code in <code>preserves/values.py</code> <pre><code>def __init__(self, key, fields):\n self.key = key\n self.fields = tuple(fields)\n self.__hash = None\n</code></pre>"},{"location":"values/#preserves.values.Record.makeBasicConstructor","title":"<code>makeBasicConstructor(label, fieldNames)</code> <code>staticmethod</code>","text":"<p>Constructs and returns a \"constructor\" for <code>Record</code>s having a certain <code>label</code> and number of fields.</p> Deprecated <p>Use preserves.schema definitions instead.</p> <p>The \"constructor\" is a callable function that accepts <code>len(fields)</code> arguments and returns a Record with <code>label</code> as its label and the arguments to the constructor as field values.</p> <p>In addition, the \"constructor\" has a <code>constructorInfo</code> attribute holding a RecordConstructorInfo object, an <code>isClassOf</code> attribute holding a unary function that returns <code>True</code> iff its argument is a Record with label <code>label</code> and arity <code>len(fieldNames)</code>, and an <code>ensureClassOf</code> attribute that raises an <code>Exception</code> if <code>isClassOf</code> returns false on its argument and returns the argument otherwise.</p> <p>Finally, for each field name <code>f</code> in <code>fieldNames</code>, the \"constructor\" object has an attribute <code>_f</code> that is a unary function that retrieves the <code>f</code> field from the passed in argument.</p> <pre><code>&gt;&gt;&gt; c = Record.makeBasicConstructor(Symbol('date'), 'year month day')\n&gt;&gt;&gt; c(1969, 7, 16)\n#date(1969, 7, 16)\n&gt;&gt;&gt; c.constructorInfo\n#date/3\n&gt;&gt;&gt; c.isClassOf(c(1969, 7, 16))\nTrue\n&gt;&gt;&gt; c.isClassOf(Record(Symbol('date'), [1969, 7, 16]))\nTrue\n&gt;&gt;&gt; c.isClassOf(Record(Symbol('date'), [1969]))\nFalse\n&gt;&gt;&gt; c.ensureClassOf(c(1969, 7, 16))\n#date(1969, 7, 16)\n&gt;&gt;&gt; c.ensureClassOf(Record(Symbol('date'), [1969]))\nTraceback (most recent call last):\n ...\nTypeError: Record: expected #date/3, got #date(1969)\n&gt;&gt;&gt; c._year(c(1969, 7, 16))\n1969\n&gt;&gt;&gt; c._month(c(1969, 7, 16))\n7\n&gt;&gt;&gt; c._day(c(1969, 7, 16))\n16\n</code></pre> <p>Parameters:</p> Name Type Description Default <code>label</code> <code>Value</code> <p>Label to use for constructed/matched <code>Record</code>s</p> required <code>fieldNames</code> <code>tuple[str] | list[str] | str</code> <p>Names of the <code>Record</code>'s fields</p> required Source code in <code>preserves/values.py</code> <pre><code>@staticmethod\ndef makeBasicConstructor(label, fieldNames):\n \"\"\"Constructs and returns a \"constructor\" for `Record`s having a certain `label` and\n number of fields.\n\n Deprecated:\n Use [preserves.schema][] definitions instead.\n\n The \"constructor\" is a callable function that accepts `len(fields)` arguments and\n returns a [Record][preserves.values.Record] with `label` as its label and the arguments\n to the constructor as field values.\n\n In addition, the \"constructor\" has a `constructorInfo` attribute holding a\n [RecordConstructorInfo][preserves.values.RecordConstructorInfo] object, an `isClassOf`\n attribute holding a unary function that returns `True` iff its argument is a\n [Record][preserves.values.Record] with label `label` and arity `len(fieldNames)`, and\n an `ensureClassOf` attribute that raises an `Exception` if `isClassOf` returns false on\n its argument and returns the argument otherwise.\n\n Finally, for each field name `f` in `fieldNames`, the \"constructor\" object has an\n attribute `_f` that is a unary function that retrieves the `f` field from the passed in\n argument.\n\n ```python\n &gt;&gt;&gt; c = Record.makeBasicConstructor(Symbol('date'), 'year month day')\n &gt;&gt;&gt; c(1969, 7, 16)\n #date(1969, 7, 16)\n &gt;&gt;&gt; c.constructorInfo\n #date/3\n &gt;&gt;&gt; c.isClassOf(c(1969, 7, 16))\n True\n &gt;&gt;&gt; c.isClassOf(Record(Symbol('date'), [1969, 7, 16]))\n True\n &gt;&gt;&gt; c.isClassOf(Record(Symbol('date'), [1969]))\n False\n &gt;&gt;&gt; c.ensureClassOf(c(1969, 7, 16))\n #date(1969, 7, 16)\n &gt;&gt;&gt; c.ensureClassOf(Record(Symbol('date'), [1969]))\n Traceback (most recent call last):\n ...\n TypeError: Record: expected #date/3, got #date(1969)\n &gt;&gt;&gt; c._year(c(1969, 7, 16))\n 1969\n &gt;&gt;&gt; c._month(c(1969, 7, 16))\n 7\n &gt;&gt;&gt; c._day(c(1969, 7, 16))\n 16\n\n ```\n\n Args:\n label (Value): Label to use for constructed/matched `Record`s\n fieldNames (tuple[str] | list[str] | str): Names of the `Record`'s fields\n\n \"\"\"\n if type(fieldNames) == str:\n fieldNames = fieldNames.split()\n arity = len(fieldNames)\n def ctor(*fields):\n if len(fields) != arity:\n raise Exception(\"Record: cannot instantiate %r expecting %d fields with %d fields\"%(\n label,\n arity,\n len(fields)))\n return Record(label, fields)\n ctor.constructorInfo = RecordConstructorInfo(label, arity)\n ctor.isClassOf = lambda v: \\\n isinstance(v, Record) and v.key == label and len(v.fields) == arity\n def ensureClassOf(v):\n if not ctor.isClassOf(v):\n raise TypeError(\"Record: expected %r/%d, got %r\" % (label, arity, v))\n return v\n ctor.ensureClassOf = ensureClassOf\n for fieldIndex in range(len(fieldNames)):\n fieldName = fieldNames[fieldIndex]\n # Stupid python scoping bites again\n def getter(fieldIndex):\n return lambda v: ensureClassOf(v)[fieldIndex]\n setattr(ctor, '_' + fieldName, getter(fieldIndex))\n return ctor\n</code></pre>"},{"location":"values/#preserves.values.Record.makeConstructor","title":"<code>makeConstructor(labelSymbolText, fieldNames)</code> <code>staticmethod</code>","text":"<p>Equivalent to <code>Record.makeBasicConstructor(Symbol(labelSymbolText), fieldNames)</code>.</p> Deprecated <p>Use preserves.schema definitions instead.</p> Source code in <code>preserves/values.py</code> <pre><code>@staticmethod\ndef makeConstructor(labelSymbolText, fieldNames):\n \"\"\"\n Equivalent to `Record.makeBasicConstructor(Symbol(labelSymbolText), fieldNames)`.\n\n Deprecated:\n Use [preserves.schema][] definitions instead.\n \"\"\"\n return Record.makeBasicConstructor(Symbol(labelSymbolText), fieldNames)\n</code></pre>"},{"location":"values/#preserves.values.RecordConstructorInfo","title":"<code>RecordConstructorInfo(key, arity)</code>","text":"<p> Bases: <code>object</code></p> <p>Describes the shape of a <code>Record</code> constructor, namely its label and its arity (field count).</p> <pre><code>&gt;&gt;&gt; RecordConstructorInfo(Symbol('label'), 3)\n#label/3\n</code></pre> <p>Attributes:</p> Name Type Description <code>key</code> <code>Value</code> <p>the label of matching <code>Record</code>s</p> <code>arity</code> <code>int</code> <p>the number of fields in matching <code>Record</code>s</p> Source code in <code>preserves/values.py</code> <pre><code>def __init__(self, key, arity):\n self.key = key\n self.arity = arity\n</code></pre>"},{"location":"values/#preserves.values.Symbol","title":"<code>Symbol(name)</code>","text":"<p> Bases: <code>object</code></p> <p>Representation of Preserves <code>Symbol</code>s.</p> <pre><code>&gt;&gt;&gt; Symbol('xyz')\n#xyz\n&gt;&gt;&gt; Symbol('xyz').name\n'xyz'\n&gt;&gt;&gt; repr(Symbol('xyz'))\n'#xyz'\n&gt;&gt;&gt; str(Symbol('xyz'))\n'xyz'\n&gt;&gt;&gt; import preserves\n&gt;&gt;&gt; preserves.stringify(Symbol('xyz'))\n'xyz'\n&gt;&gt;&gt; preserves.stringify(Symbol('hello world'))\n'|hello world|'\n&gt;&gt;&gt; preserves.parse('xyz')\n#xyz\n&gt;&gt;&gt; preserves.parse('|hello world|')\n#hello world\n</code></pre> <p>Attributes:</p> Name Type Description <code>name</code> <code>str | Symbol</code> <p>The symbol's text label. If an existing Symbol is passed in, the existing Symbol's <code>name</code> is used as the <code>name</code> for the new Symbol.</p> Source code in <code>preserves/values.py</code> <pre><code>def __init__(self, name):\n self.name = name.name if isinstance(name, Symbol) else name\n</code></pre>"},{"location":"values/#preserves.values.annotate","title":"<code>annotate(v, *anns)</code>","text":"<p>Wraps <code>v</code> in an Annotated object, if it isn't already wrapped, and appends each of the <code>anns</code> to the Annotated's <code>annotations</code> sequence. NOTE: Does not recursively ensure that any parts of the argument <code>v</code> are themselves wrapped in Annotated objects!</p> <pre><code>&gt;&gt;&gt; import preserves\n&gt;&gt;&gt; print(preserves.stringify(annotate(123, \"A comment\", \"Another comment\")))\n@\"A comment\" @\"Another comment\" 123\n</code></pre> Source code in <code>preserves/values.py</code> <pre><code>def annotate(v, *anns):\n \"\"\"Wraps `v` in an [Annotated][preserves.values.Annotated] object, if it isn't already\n wrapped, and appends each of the `anns` to the [Annotated][preserves.values.Annotated]'s\n `annotations` sequence. NOTE: Does not recursively ensure that any parts of the argument\n `v` are themselves wrapped in [Annotated][preserves.values.Annotated] objects!\n\n ```python\n &gt;&gt;&gt; import preserves\n &gt;&gt;&gt; print(preserves.stringify(annotate(123, \"A comment\", \"Another comment\")))\n @\"A comment\" @\"Another comment\" 123\n\n ```\n \"\"\"\n if not is_annotated(v):\n v = Annotated(v)\n for a in anns:\n v.annotations.append(a)\n return v\n</code></pre>"},{"location":"values/#preserves.values.cmp_floats","title":"<code>cmp_floats(a, b)</code>","text":"<p>Implements the <code>totalOrder</code> predicate defined in section 5.10 of IEEE Std 754-2008.</p> Source code in <code>preserves/values.py</code> <pre><code>def cmp_floats(a, b):\n \"\"\"Implements the `totalOrder` predicate defined in section 5.10 of [IEEE Std\n 754-2008](https://dx.doi.org/10.1109/IEEESTD.2008.4610935).\n\n \"\"\"\n a = float_to_int(a)\n b = float_to_int(b)\n if a &amp; 0x8000000000000000: a = a ^ 0x7fffffffffffffff\n if b &amp; 0x8000000000000000: b = b ^ 0x7fffffffffffffff\n return a - b\n</code></pre>"},{"location":"values/#preserves.values.dict_kvs","title":"<code>dict_kvs(d)</code>","text":"<p>Generator function yielding a sequence of alternating keys and values from <code>d</code>. In some sense the inverse of ImmutableDict.from_kvs.</p> <pre><code>&gt;&gt;&gt; list(dict_kvs({'a': 1, 'b': 2}))\n['a', 1, 'b', 2]\n</code></pre> Source code in <code>preserves/values.py</code> <pre><code>def dict_kvs(d):\n \"\"\"Generator function yielding a sequence of alternating keys and values from `d`. In some\n sense the inverse of [ImmutableDict.from_kvs][preserves.values.ImmutableDict.from_kvs].\n\n ```python\n &gt;&gt;&gt; list(dict_kvs({'a': 1, 'b': 2}))\n ['a', 1, 'b', 2]\n\n ```\n \"\"\"\n for k in d:\n yield k\n yield d[k]\n</code></pre>"},{"location":"values/#preserves.values.is_annotated","title":"<code>is_annotated(v)</code>","text":"<p><code>True</code> iff <code>v</code> is an instance of Annotated.</p> Source code in <code>preserves/values.py</code> <pre><code>def is_annotated(v):\n \"\"\"`True` iff `v` is an instance of [Annotated][preserves.values.Annotated].\"\"\"\n return isinstance(v, Annotated)\n</code></pre>"},{"location":"values/#preserves.values.preserve","title":"<code>preserve(v)</code>","text":"<p>Converts <code>v</code> to a representation of a Preserves <code>Value</code> by (repeatedly) setting</p> <pre><code>v = v.__preserve__()\n</code></pre> <p>while <code>v</code> has a <code>__preserve__</code> method. Parsed Schema values are able to render themselves to their serialized representations this way.</p> Source code in <code>preserves/values.py</code> <pre><code>def preserve(v):\n \"\"\"Converts `v` to a representation of a Preserves `Value` by (repeatedly) setting\n\n ```python\n v = v.__preserve__()\n ```\n\n while `v` has a `__preserve__` method. Parsed [Schema][preserves.schema]\n values are able to render themselves to their serialized representations this way.\n\n \"\"\"\n while hasattr(v, '__preserve__'):\n v = v.__preserve__()\n return v\n</code></pre>"},{"location":"values/#preserves.values.strip_annotations","title":"<code>strip_annotations(v, depth=inf)</code>","text":"<p>Exposes <code>depth</code> layers of raw structure of potentially-Annotated <code>Value</code>s. If <code>depth==0</code> or <code>v</code> is not Annotated, just returns <code>v</code>. Otherwise, descends recursively into the structure of <code>v.item</code>.</p> <pre><code>&gt;&gt;&gt; import preserves\n&gt;&gt;&gt; a = preserves.parse('@\"A comment\" [@a 1 @b 2 @c 3]', include_annotations=True)\n&gt;&gt;&gt; is_annotated(a)\nTrue\n&gt;&gt;&gt; print(preserves.stringify(a))\n@\"A comment\" [@a 1 @b 2 @c 3]\n&gt;&gt;&gt; print(preserves.stringify(strip_annotations(a)))\n[1 2 3]\n&gt;&gt;&gt; print(preserves.stringify(strip_annotations(a, depth=1)))\n[@a 1 @b 2 @c 3]\n</code></pre> Source code in <code>preserves/values.py</code> <pre><code>def strip_annotations(v, depth=inf):\n \"\"\"Exposes `depth` layers of raw structure of\n potentially-[Annotated][preserves.values.Annotated] `Value`s. If `depth==0` or `v` is not\n [Annotated][preserves.values.Annotated], just returns `v`. Otherwise, descends recursively\n into the structure of `v.item`.\n\n ```python\n &gt;&gt;&gt; import preserves\n &gt;&gt;&gt; a = preserves.parse('@\"A comment\" [@a 1 @b 2 @c 3]', include_annotations=True)\n &gt;&gt;&gt; is_annotated(a)\n True\n &gt;&gt;&gt; print(preserves.stringify(a))\n @\"A comment\" [@a 1 @b 2 @c 3]\n &gt;&gt;&gt; print(preserves.stringify(strip_annotations(a)))\n [1 2 3]\n &gt;&gt;&gt; print(preserves.stringify(strip_annotations(a, depth=1)))\n [@a 1 @b 2 @c 3]\n\n ```\n \"\"\"\n\n if depth == 0: return v\n if not is_annotated(v): return v\n\n next_depth = depth - 1\n def walk(v):\n return strip_annotations(v, next_depth)\n\n v = v.item\n if isinstance(v, Record):\n return Record(strip_annotations(v.key, depth), tuple(walk(f) for f in v.fields))\n elif isinstance(v, list):\n return tuple(walk(f) for f in v)\n elif isinstance(v, tuple):\n return tuple(walk(f) for f in v)\n elif isinstance(v, set):\n return frozenset(walk(f) for f in v)\n elif isinstance(v, frozenset):\n return frozenset(walk(f) for f in v)\n elif isinstance(v, dict):\n return ImmutableDict.from_kvs(walk(f) for f in dict_kvs(v))\n elif is_annotated(v):\n raise ValueError('Improper annotation structure')\n else:\n return v\n</code></pre>"}]}