preserves/python/0.18.0/search/search_index.json

1 line
78 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 | Float\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 Float and 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>Float</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: 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: 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'\\xa0{\\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'\\xa0{\\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'\\xa0{\\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'\\xa0{\\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'\\xa0{\\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'\\xa0{\\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 == 0x82: return self.wrap(Float.from_bytes(self.nextbytes(4)))\n if tag == 0x83: return self.wrap(struct.unpack('&gt;d', self.nextbytes(8))[0])\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 &gt;= 0x90 and tag &lt;= 0x9f: return self.wrap(tag - (0xa0 if tag &gt; 0x9c else 0x90))\n if tag &gt;= 0xa0 and tag &lt;= 0xaf: return self.wrap(self.nextint(tag - 0xa0 + 1))\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: 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'\\xa0{\\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: 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(0x83)\n self.buffer.extend(struct.pack('&gt;d', v))\n elif isinstance(v, numbers.Number):\n if v &gt;= -3 and v &lt;= 12:\n self.buffer.append(0x90 + (v if v &gt;= 0 else v + 16))\n else:\n self.encodeint(v)\n elif isinstance(v, bytes):\n self.encodebytes(2, v)\n elif isinstance(v, basestring_):\n self.encodebytes(1, v.encode('utf-8'))\n elif isinstance(v, list):\n self.encodevalues(5, v)\n elif isinstance(v, tuple):\n self.encodevalues(5, 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(5, 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: 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}]))\na(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>TODO (document main behaviour)</p>"},{"location":"path/#preserves.path.Predicate","title":"<code>Predicate = syntax.Predicate</code> <code>module-attribute</code>","text":"<p>TODO</p>"},{"location":"path/#preserves.path.Selector","title":"<code>Selector = syntax.Selector</code> <code>module-attribute</code>","text":"<p>TODO</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>TODO</p>"},{"location":"path/#preserves.path.parse","title":"<code>parse(s)</code>","text":"<p>TODO</p> Source code in <code>preserves/path.py</code> <pre><code>def parse(s):\n\"\"\"TODO\"\"\"\n return parse_selector(Parser(s))\n</code></pre>"},{"location":"schema/","title":"Preserves Schema","text":"<p>This is an implementation of Preserves Schema for Python 3.</p> <p>TODO</p>"},{"location":"schema/#preserves.schema.meta","title":"<code>meta = load_schema_file(__metaschema_filename).schema</code> <code>module-attribute</code>","text":"<p>TODO</p>"},{"location":"schema/#preserves.schema.Compiler","title":"<code>Compiler()</code>","text":"<p>TODO</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.Definition","title":"<code>Definition(*args, **kwargs)</code>","text":"<p> Bases: <code>SchemaObject</code></p> <p>TODO</p> 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.Enumeration","title":"<code>Enumeration()</code>","text":"<p> Bases: <code>SchemaObject</code></p> <p>TODO</p> 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.Namespace","title":"<code>Namespace(prefix)</code>","text":"<p>TODO</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>TODO</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>TODO</p>"},{"location":"schema/#preserves.schema.SchemaObject.__preserve__","title":"<code>__preserve__()</code>","text":"<p>TODO</p> Source code in <code>preserves/schema.py</code> <pre><code>def __preserve__(self):\n\"\"\"TODO\"\"\"\n raise NotImplementedError('Subclass responsibility')\n</code></pre>"},{"location":"schema/#preserves.schema.SchemaObject.decode","title":"<code>decode(v)</code> <code>classmethod</code>","text":"<p>TODO</p> Source code in <code>preserves/schema.py</code> <pre><code>@classmethod\ndef decode(cls, v):\n\"\"\"TODO\"\"\"\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>TODO</p> Source code in <code>preserves/schema.py</code> <pre><code>@classmethod\ndef try_decode(cls, v):\n\"\"\"TODO\"\"\"\n try:\n return cls.decode(v)\n except SchemaDecodeFailed:\n return None\n</code></pre>"},{"location":"schema/#preserves.schema.encode","title":"<code>encode(p, v)</code>","text":"<p>TODO</p> Source code in <code>preserves/schema.py</code> <pre><code>def encode(p, v):\n\"\"\"TODO\"\"\"\n if hasattr(v, '__escape_schema__'):\n return preserve(v.__escape_schema__())\n if p == ANY:\n return v\n if p.key == NAMED:\n return encode(p[1], safegetattr(v, p[0].name))\n if p.key == ATOM:\n return v\n if p.key == EMBEDDED:\n return Embedded(v)\n if p.key == LIT:\n return p[0]\n if p.key == SEQOF:\n return tuple(encode(p[0], w) for w in v)\n if p.key == SETOF:\n return set(encode(p[0], w) for w in v)\n if p.key == DICTOF:\n return dict((encode(p[0], k), encode(p[1], w)) for (k, w) in v.items())\n if p.key == REF:\n return preserve(v)\n if p.key == REC:\n return Record(encode(p[0], v), encode(p[1], v))\n if p.key == TUPLE:\n return tuple(encode(pp, v) for pp in p[0])\n if p.key == TUPLE_PREFIX:\n return tuple(encode(pp, v) for pp in p[0]) + encode(p[1], v)\n if p.key == DICT:\n return dict((k, encode(pp, v)) for (k, pp) in p[0].items())\n if p.key == AND:\n return merge(*[encode(pp, v) for pp in p[0]])\n raise ValueError(f'Bad schema {p}')\n</code></pre>"},{"location":"schema/#preserves.schema.extend","title":"<code>extend(cls)</code>","text":"<p>TODO</p> Source code in <code>preserves/schema.py</code> <pre><code>def extend(cls):\n\"\"\"TODO\"\"\"\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>TODO</p> Source code in <code>preserves/schema.py</code> <pre><code>def load_schema_file(filename):\n\"\"\"TODO\"\"\"\n c = Compiler()\n c.load(filename)\n return c.root\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: 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: 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: 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: 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 in ';@':\n annotations = self.gather_annotations()\n v = self.next()\n if self.include_annotations:\n v.annotations = annotations + v.annotations\n return v\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 == 'f': return self.wrap(False)\n if c == 't': return self.wrap(True)\n if c == '{': return self.wrap(frozenset(self.upto('}')))\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 == 'f': return self.wrap(self.read_hex_float(4))\n if c == 'd': return self.wrap(self.read_hex_float(8))\n raise DecodeError('Invalid #x syntax')\n if c == '[': return self.wrap(self.read_base64_binary())\n if c == '=':\n old_ann = self.include_annotations\n self.include_annotations = True\n bs_val = self.next()\n self.include_annotations = old_ann\n if len(bs_val.annotations) &gt; 0:\n raise DecodeError('Annotations not permitted after #=')\n bs_val = bs_val.item\n if not isinstance(bs_val, bytes):\n raise DecodeError('ByteString must follow #=')\n return self.wrap(Decoder(bs_val, include_annotations = self.include_annotations).next())\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;')\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(']'))\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 Float and 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.Float","title":"<code>Float(value)</code>","text":"<p> Bases: <code>object</code></p> <p>Wrapper for treating a Python double-precision floating-point value as a single-precision (32-bit) float, from Preserves' perspective. (Python lacks native single-precision floating point support.)</p> <pre><code>&gt;&gt;&gt; Float(3.45)\nFloat(3.45)\n&gt;&gt;&gt; import preserves\n&gt;&gt;&gt; preserves.stringify(Float(3.45))\n'3.45f'\n&gt;&gt;&gt; preserves.stringify(3.45)\n'3.45'\n&gt;&gt;&gt; preserves.parse('3.45f')\nFloat(3.45)\n&gt;&gt;&gt; preserves.parse('3.45')\n3.45\n&gt;&gt;&gt; preserves.encode(Float(3.45))\nb'\\x82@\\\\\\xcc\\xcd'\n&gt;&gt;&gt; preserves.encode(3.45)\nb'\\x83@\\x0b\\x99\\x99\\x99\\x99\\x99\\x9a'\n</code></pre> <p>Attributes:</p> Name Type Description <code>value</code> <code>float</code> <p>the double-precision representation of intended single-precision value</p> Source code in <code>preserves/values.py</code> <pre><code>def __init__(self, value):\n self.value = value\n</code></pre>"},{"location":"values/#preserves.values.Float.from_bytes","title":"<code>from_bytes(bs)</code> <code>staticmethod</code>","text":"<p>Converts a 4-byte-long byte string to a 32-bit single-precision floating point value wrapped in a Float instance. Takes care to preserve the quiet/signalling bit-pattern of NaN values, unlike its <code>struct.unpack('&gt;f', ...)</code> equivalent.</p> <pre><code>&gt;&gt;&gt; Float.from_bytes(b'\\x7f\\x80\\x00{')\nFloat(nan)\n&gt;&gt;&gt; Float.from_bytes(b'\\x7f\\x80\\x00{').to_bytes()\nb'\\x7f\\x80\\x00{'\n\n&gt;&gt;&gt; struct.unpack('&gt;f', b'\\x7f\\x80\\x00{')[0]\nnan\n&gt;&gt;&gt; Float(struct.unpack('&gt;f', b'\\x7f\\x80\\x00{')[0]).to_bytes()\nb'\\x7f\\xc0\\x00{'\n&gt;&gt;&gt; struct.pack('&gt;f', struct.unpack('&gt;f', b'\\x7f\\x80\\x00{')[0])\nb'\\x7f\\xc0\\x00{'\n</code></pre> <p>(Note well the difference between <code>7f80007b</code> and <code>7fc0007b</code>!)</p> Source code in <code>preserves/values.py</code> <pre><code>@staticmethod\ndef from_bytes(bs):\n\"\"\"Converts a 4-byte-long byte string to a 32-bit single-precision floating point value\n wrapped in a [Float][preserves.values.Float] instance. Takes care to preserve the\n quiet/signalling bit-pattern of NaN values, unlike its `struct.unpack('&gt;f', ...)`\n equivalent.\n\n ```python\n &gt;&gt;&gt; Float.from_bytes(b'\\\\x7f\\\\x80\\\\x00{')\n Float(nan)\n &gt;&gt;&gt; Float.from_bytes(b'\\\\x7f\\\\x80\\\\x00{').to_bytes()\n b'\\\\x7f\\\\x80\\\\x00{'\n\n &gt;&gt;&gt; struct.unpack('&gt;f', b'\\\\x7f\\\\x80\\\\x00{')[0]\n nan\n &gt;&gt;&gt; Float(struct.unpack('&gt;f', b'\\\\x7f\\\\x80\\\\x00{')[0]).to_bytes()\n b'\\\\x7f\\\\xc0\\\\x00{'\n &gt;&gt;&gt; struct.pack('&gt;f', struct.unpack('&gt;f', b'\\\\x7f\\\\x80\\\\x00{')[0])\n b'\\\\x7f\\\\xc0\\\\x00{'\n\n ```\n\n (Note well the difference between `7f80007b` and `7fc0007b`!)\n\n \"\"\"\n vf = struct.unpack('&gt;I', bs)[0]\n if (vf &amp; 0x7f800000) == 0x7f800000:\n # NaN or inf. Preserve quiet/signalling bit by manually expanding to double-precision.\n sign = vf &gt;&gt; 31\n payload = vf &amp; 0x007fffff\n dbs = struct.pack('&gt;Q', (sign &lt;&lt; 63) | 0x7ff0000000000000 | (payload &lt;&lt; 29))\n return Float(struct.unpack('&gt;d', dbs)[0])\n else:\n return Float(struct.unpack('&gt;f', bs)[0])\n</code></pre>"},{"location":"values/#preserves.values.Float.to_bytes","title":"<code>to_bytes()</code>","text":"<p>Converts this 32-bit single-precision floating point value to its binary32 format, taking care to preserve the quiet/signalling bit-pattern of NaN values, unlike its <code>struct.pack('&gt;f', ...)</code> equivalent.</p> <pre><code>&gt;&gt;&gt; Float.from_bytes(b'\\x7f\\x80\\x00{')\nFloat(nan)\n&gt;&gt;&gt; Float.from_bytes(b'\\x7f\\x80\\x00{').to_bytes()\nb'\\x7f\\x80\\x00{'\n\n&gt;&gt;&gt; struct.unpack('&gt;f', b'\\x7f\\x80\\x00{')[0]\nnan\n&gt;&gt;&gt; Float(struct.unpack('&gt;f', b'\\x7f\\x80\\x00{')[0]).to_bytes()\nb'\\x7f\\xc0\\x00{'\n&gt;&gt;&gt; struct.pack('&gt;f', struct.unpack('&gt;f', b'\\x7f\\x80\\x00{')[0])\nb'\\x7f\\xc0\\x00{'\n</code></pre> <p>(Note well the difference between <code>7f80007b</code> and <code>7fc0007b</code>!)</p> Source code in <code>preserves/values.py</code> <pre><code>def to_bytes(self):\n\"\"\"Converts this 32-bit single-precision floating point value to its binary32 format,\n taking care to preserve the quiet/signalling bit-pattern of NaN values, unlike its\n `struct.pack('&gt;f', ...)` equivalent.\n\n ```python\n &gt;&gt;&gt; Float.from_bytes(b'\\\\x7f\\\\x80\\\\x00{')\n Float(nan)\n &gt;&gt;&gt; Float.from_bytes(b'\\\\x7f\\\\x80\\\\x00{').to_bytes()\n b'\\\\x7f\\\\x80\\\\x00{'\n\n &gt;&gt;&gt; struct.unpack('&gt;f', b'\\\\x7f\\\\x80\\\\x00{')[0]\n nan\n &gt;&gt;&gt; Float(struct.unpack('&gt;f', b'\\\\x7f\\\\x80\\\\x00{')[0]).to_bytes()\n b'\\\\x7f\\\\xc0\\\\x00{'\n &gt;&gt;&gt; struct.pack('&gt;f', struct.unpack('&gt;f', b'\\\\x7f\\\\x80\\\\x00{')[0])\n b'\\\\x7f\\\\xc0\\\\x00{'\n\n ```\n\n (Note well the difference between `7f80007b` and `7fc0007b`!)\n\n \"\"\"\n\n if math.isnan(self.value) or math.isinf(self.value):\n dbs = struct.pack('&gt;d', self.value)\n vd = struct.unpack('&gt;Q', dbs)[0]\n sign = vd &gt;&gt; 63\n payload = (vd &gt;&gt; 29) &amp; 0x007fffff\n vf = (sign &lt;&lt; 31) | 0x7f800000 | payload\n return struct.pack('&gt;I', vf)\n else:\n return struct.pack('&gt;f', self.value)\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 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; 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</code> <p>the symbol's text label</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>"}]}