From 3313674f1560338e095c2826c1e793bed42f6793 Mon Sep 17 00:00:00 2001 From: Tony Garnock-Jones Date: Wed, 1 Nov 2023 14:47:11 +0100 Subject: [PATCH] New python version 0.992.0 --- _data/python-versions.json | 1 + implementations/python/setup.py | 2 +- python/0.992.0/404.html | 437 ++ python/0.992.0/api/index.html | 698 ++ python/0.992.0/assets/_mkdocstrings.css | 36 + python/0.992.0/assets/images/favicon.png | Bin 0 -> 1870 bytes .../assets/javascripts/bundle.efa0ade1.min.js | 29 + .../javascripts/bundle.efa0ade1.min.js.map | 8 + .../javascripts/lunr/min/lunr.ar.min.js | 1 + .../javascripts/lunr/min/lunr.da.min.js | 18 + .../javascripts/lunr/min/lunr.de.min.js | 18 + .../javascripts/lunr/min/lunr.du.min.js | 18 + .../javascripts/lunr/min/lunr.es.min.js | 18 + .../javascripts/lunr/min/lunr.fi.min.js | 18 + .../javascripts/lunr/min/lunr.fr.min.js | 18 + .../javascripts/lunr/min/lunr.hi.min.js | 1 + .../javascripts/lunr/min/lunr.hu.min.js | 18 + .../javascripts/lunr/min/lunr.it.min.js | 18 + .../javascripts/lunr/min/lunr.ja.min.js | 1 + .../javascripts/lunr/min/lunr.jp.min.js | 1 + .../javascripts/lunr/min/lunr.ko.min.js | 1 + .../javascripts/lunr/min/lunr.multi.min.js | 1 + .../javascripts/lunr/min/lunr.nl.min.js | 18 + .../javascripts/lunr/min/lunr.no.min.js | 18 + .../javascripts/lunr/min/lunr.pt.min.js | 18 + .../javascripts/lunr/min/lunr.ro.min.js | 18 + .../javascripts/lunr/min/lunr.ru.min.js | 18 + .../lunr/min/lunr.stemmer.support.min.js | 1 + .../javascripts/lunr/min/lunr.sv.min.js | 18 + .../javascripts/lunr/min/lunr.ta.min.js | 1 + .../javascripts/lunr/min/lunr.th.min.js | 1 + .../javascripts/lunr/min/lunr.tr.min.js | 18 + .../javascripts/lunr/min/lunr.vi.min.js | 1 + .../javascripts/lunr/min/lunr.zh.min.js | 1 + .../assets/javascripts/lunr/tinyseg.js | 206 + .../assets/javascripts/lunr/wordcut.js | 6708 +++++++++++++++++ .../workers/search.208ed371.min.js | 42 + .../workers/search.208ed371.min.js.map | 8 + .../assets/stylesheets/main.c4a75a56.min.css | 1 + .../stylesheets/main.c4a75a56.min.css.map | 1 + .../stylesheets/palette.a0c5b2b5.min.css | 1 + .../stylesheets/palette.a0c5b2b5.min.css.map | 1 + python/0.992.0/binary/index.html | 1568 ++++ python/0.992.0/compare/index.html | 858 +++ python/0.992.0/error/index.html | 678 ++ python/0.992.0/fold/index.html | 651 ++ python/0.992.0/index.html | 592 ++ python/0.992.0/merge/index.html | 795 ++ python/0.992.0/objects.inv | Bin 0 -> 912 bytes python/0.992.0/path/index.html | 979 +++ python/0.992.0/schema/index.html | 2378 ++++++ python/0.992.0/search/search_index.json | 1 + python/0.992.0/sitemap.xml | 58 + .../syndicate-protocols-schema-bundle.bin | 40 + python/0.992.0/text/index.html | 1557 ++++ python/0.992.0/values/index.html | 2555 +++++++ 56 files changed, 21169 insertions(+), 1 deletion(-) create mode 100644 python/0.992.0/404.html create mode 100644 python/0.992.0/api/index.html create mode 100644 python/0.992.0/assets/_mkdocstrings.css create mode 100644 python/0.992.0/assets/images/favicon.png create mode 100644 python/0.992.0/assets/javascripts/bundle.efa0ade1.min.js create mode 100644 python/0.992.0/assets/javascripts/bundle.efa0ade1.min.js.map create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.ar.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.da.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.de.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.du.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.es.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.fi.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.fr.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.hi.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.hu.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.it.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.ja.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.jp.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.ko.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.multi.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.nl.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.no.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.pt.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.ro.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.ru.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.stemmer.support.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.sv.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.ta.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.th.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.tr.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.vi.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/min/lunr.zh.min.js create mode 100644 python/0.992.0/assets/javascripts/lunr/tinyseg.js create mode 100644 python/0.992.0/assets/javascripts/lunr/wordcut.js create mode 100644 python/0.992.0/assets/javascripts/workers/search.208ed371.min.js create mode 100644 python/0.992.0/assets/javascripts/workers/search.208ed371.min.js.map create mode 100644 python/0.992.0/assets/stylesheets/main.c4a75a56.min.css create mode 100644 python/0.992.0/assets/stylesheets/main.c4a75a56.min.css.map create mode 100644 python/0.992.0/assets/stylesheets/palette.a0c5b2b5.min.css create mode 100644 python/0.992.0/assets/stylesheets/palette.a0c5b2b5.min.css.map create mode 100644 python/0.992.0/binary/index.html create mode 100644 python/0.992.0/compare/index.html create mode 100644 python/0.992.0/error/index.html create mode 100644 python/0.992.0/fold/index.html create mode 100644 python/0.992.0/index.html create mode 100644 python/0.992.0/merge/index.html create mode 100644 python/0.992.0/objects.inv create mode 100644 python/0.992.0/path/index.html create mode 100644 python/0.992.0/schema/index.html create mode 100644 python/0.992.0/search/search_index.json create mode 100644 python/0.992.0/sitemap.xml create mode 100644 python/0.992.0/syndicate-protocols-schema-bundle.bin create mode 100644 python/0.992.0/text/index.html create mode 100644 python/0.992.0/values/index.html diff --git a/_data/python-versions.json b/_data/python-versions.json index bb1acb8..79880b3 100644 --- a/_data/python-versions.json +++ b/_data/python-versions.json @@ -1,4 +1,5 @@ [ + {"version":"0.992.0","title":"0.992.0","aliases":[]}, {"version":"0.991.0","title":"0.991.0","aliases":["latest"]}, {"version":"0.990.1","title":"0.990.1","aliases":[]}, {"version":"0.990.0","title":"0.990.0","aliases":[]}, diff --git a/implementations/python/setup.py b/implementations/python/setup.py index 2afb8f3..885e742 100644 --- a/implementations/python/setup.py +++ b/implementations/python/setup.py @@ -2,7 +2,7 @@ from setuptools import setup setup( name="preserves", - version="0.991.0", + version="0.992.0", author="Tony Garnock-Jones", author_email="tonyg@leastfixedpoint.com", license="Apache Software License", diff --git a/python/0.992.0/404.html b/python/0.992.0/404.html new file mode 100644 index 0000000..abe23d2 --- /dev/null +++ b/python/0.992.0/404.html @@ -0,0 +1,437 @@ + + + + + + + + + + + + + + + + + + Python Preserves + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+ +
+ + + + + + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ +

404 - Not found

+ +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/python/0.992.0/api/index.html b/python/0.992.0/api/index.html new file mode 100644 index 0000000..bdca213 --- /dev/null +++ b/python/0.992.0/api/index.html @@ -0,0 +1,698 @@ + + + + + + + + + + + + + + + + + + + + + + + + The top-level preserves package - Python Preserves + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + Skip to content + + +
+
+ +
+ + + + + + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + +

The top-level preserves package

+ + +
+ + + +
+ +
import preserves
+
+

The main package re-exports a subset of the exports of its constituent modules:

+ +

It also exports the compare and fold modules themselves, +permitting patterns like

+
>>> from preserves import *
+>>> compare.cmp(123, 234)
+-1
+
+

Finally, it provides a few utility aliases for common tasks:

+ + + +
+ + + + + + + +
+ + + +

+dumps = stringify + + + module-attribute + + +

+ + +
+ +

This alias for stringify provides a familiar pythonesque name for converting a Preserves Value to a string.

+
+ +
+ +
+ + + +

+loads = parse + + + module-attribute + + +

+ + +
+ +

This alias for parse provides a familiar pythonesque name for converting a string to a Preserves Value.

+
+ +
+ + + + + +
+ +
+ +
+ +
+
+ + + Last update: + March 16, 2023 + +
+ Created: + March 16, 2023 + + +
+
+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/python/0.992.0/assets/_mkdocstrings.css b/python/0.992.0/assets/_mkdocstrings.css new file mode 100644 index 0000000..a65078d --- /dev/null +++ b/python/0.992.0/assets/_mkdocstrings.css @@ -0,0 +1,36 @@ + +/* Don't capitalize names. */ +h5.doc-heading { + text-transform: none !important; +} + +/* Avoid breaking parameters name, etc. in table cells. */ +.doc-contents td code { + word-break: normal !important; +} + +/* For pieces of Markdown rendered in table cells. */ +.doc-contents td p { + margin-top: 0 !important; + margin-bottom: 0 !important; +} + +/* Max width for docstring sections tables. */ +.doc .md-typeset__table, +.doc .md-typeset__table table { + display: table !important; + width: 100%; +} +.doc .md-typeset__table tr { + display: table-row; +} + +/* Avoid line breaks in rendered fields. */ +.field-body p { + display: inline; +} + +/* Defaults in Spacy table style. */ +.doc-param-default { + float: right; +} diff --git a/python/0.992.0/assets/images/favicon.png b/python/0.992.0/assets/images/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..1cf13b9f9d978896599290a74f77d5dbe7d1655c GIT binary patch literal 1870 zcmV-U2eJ5xP)Gc)JR9QMau)O=X#!i9;T z37kk-upj^(fsR36MHs_+1RCI)NNu9}lD0S{B^g8PN?Ww(5|~L#Ng*g{WsqleV}|#l zz8@ri&cTzw_h33bHI+12+kK6WN$h#n5cD8OQt`5kw6p~9H3()bUQ8OS4Q4HTQ=1Ol z_JAocz`fLbT2^{`8n~UAo=#AUOf=SOq4pYkt;XbC&f#7lb$*7=$na!mWCQ`dBQsO0 zLFBSPj*N?#u5&pf2t4XjEGH|=pPQ8xh7tpx;US5Cx_Ju;!O`ya-yF`)b%TEt5>eP1ZX~}sjjA%FJF?h7cX8=b!DZl<6%Cv z*G0uvvU+vmnpLZ2paivG-(cd*y3$hCIcsZcYOGh{$&)A6*XX&kXZd3G8m)G$Zz-LV z^GF3VAW^Mdv!)4OM8EgqRiz~*Cji;uzl2uC9^=8I84vNp;ltJ|q-*uQwGp2ma6cY7 z;`%`!9UXO@fr&Ebapfs34OmS9^u6$)bJxrucutf>`dKPKT%%*d3XlFVKunp9 zasduxjrjs>f8V=D|J=XNZp;_Zy^WgQ$9WDjgY=z@stwiEBm9u5*|34&1Na8BMjjgf3+SHcr`5~>oz1Y?SW^=K z^bTyO6>Gar#P_W2gEMwq)ot3; zREHn~U&Dp0l6YT0&k-wLwYjb?5zGK`W6S2v+K>AM(95m2C20L|3m~rN8dprPr@t)5lsk9Hu*W z?pS990s;Ez=+Rj{x7p``4>+c0G5^pYnB1^!TL=(?HLHZ+HicG{~4F1d^5Awl_2!1jICM-!9eoLhbbT^;yHcefyTAaqRcY zmuctDopPT!%k+}x%lZRKnzykr2}}XfG_ne?nRQO~?%hkzo;@RN{P6o`&mMUWBYMTe z6i8ChtjX&gXl`nvrU>jah)2iNM%JdjqoaeaU%yVn!^70x-flljp6Q5tK}5}&X8&&G zX3fpb3E(!rH=zVI_9Gjl45w@{(ITqngWFe7@9{mX;tO25Z_8 zQHEpI+FkTU#4xu>RkN>b3Tnc3UpWzPXWm#o55GKF09j^Mh~)K7{QqbO_~(@CVq! zS<8954|P8mXN2MRs86xZ&Q4EfM@JB94b=(YGuk)s&^jiSF=t3*oNK3`rD{H`yQ?d; ztE=laAUoZx5?RC8*WKOj`%LXEkgDd>&^Q4M^z`%u0rg-It=hLCVsq!Z%^6eB-OvOT zFZ28TN&cRmgU}Elrnk43)!>Z1FCPL2K$7}gwzIc48NX}#!A1BpJP?#v5wkNprhV** z?Cpalt1oH&{r!o3eSKc&ap)iz2BTn_VV`4>9M^b3;(YY}4>#ML6{~(4mH+?%07*qo IM6N<$f(jP3KmY&$ literal 0 HcmV?d00001 diff --git a/python/0.992.0/assets/javascripts/bundle.efa0ade1.min.js b/python/0.992.0/assets/javascripts/bundle.efa0ade1.min.js new file mode 100644 index 0000000..215c901 --- /dev/null +++ b/python/0.992.0/assets/javascripts/bundle.efa0ade1.min.js @@ -0,0 +1,29 @@ +"use strict";(()=>{var Ri=Object.create;var gr=Object.defineProperty;var ki=Object.getOwnPropertyDescriptor;var Hi=Object.getOwnPropertyNames,kt=Object.getOwnPropertySymbols,Pi=Object.getPrototypeOf,yr=Object.prototype.hasOwnProperty,on=Object.prototype.propertyIsEnumerable;var nn=(e,t,r)=>t in e?gr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,P=(e,t)=>{for(var r in t||(t={}))yr.call(t,r)&&nn(e,r,t[r]);if(kt)for(var r of kt(t))on.call(t,r)&&nn(e,r,t[r]);return e};var an=(e,t)=>{var r={};for(var n in e)yr.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&kt)for(var n of kt(e))t.indexOf(n)<0&&on.call(e,n)&&(r[n]=e[n]);return r};var Ht=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var $i=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Hi(t))!yr.call(e,o)&&o!==r&&gr(e,o,{get:()=>t[o],enumerable:!(n=ki(t,o))||n.enumerable});return e};var yt=(e,t,r)=>(r=e!=null?Ri(Pi(e)):{},$i(t||!e||!e.__esModule?gr(r,"default",{value:e,enumerable:!0}):r,e));var cn=Ht((xr,sn)=>{(function(e,t){typeof xr=="object"&&typeof sn!="undefined"?t():typeof define=="function"&&define.amd?define(t):t()})(xr,function(){"use strict";function e(r){var n=!0,o=!1,i=null,s={text:!0,search:!0,url:!0,tel:!0,email:!0,password:!0,number:!0,date:!0,month:!0,week:!0,time:!0,datetime:!0,"datetime-local":!0};function a(T){return!!(T&&T!==document&&T.nodeName!=="HTML"&&T.nodeName!=="BODY"&&"classList"in T&&"contains"in T.classList)}function c(T){var Qe=T.type,De=T.tagName;return!!(De==="INPUT"&&s[Qe]&&!T.readOnly||De==="TEXTAREA"&&!T.readOnly||T.isContentEditable)}function f(T){T.classList.contains("focus-visible")||(T.classList.add("focus-visible"),T.setAttribute("data-focus-visible-added",""))}function u(T){T.hasAttribute("data-focus-visible-added")&&(T.classList.remove("focus-visible"),T.removeAttribute("data-focus-visible-added"))}function p(T){T.metaKey||T.altKey||T.ctrlKey||(a(r.activeElement)&&f(r.activeElement),n=!0)}function m(T){n=!1}function d(T){a(T.target)&&(n||c(T.target))&&f(T.target)}function h(T){a(T.target)&&(T.target.classList.contains("focus-visible")||T.target.hasAttribute("data-focus-visible-added"))&&(o=!0,window.clearTimeout(i),i=window.setTimeout(function(){o=!1},100),u(T.target))}function v(T){document.visibilityState==="hidden"&&(o&&(n=!0),G())}function G(){document.addEventListener("mousemove",N),document.addEventListener("mousedown",N),document.addEventListener("mouseup",N),document.addEventListener("pointermove",N),document.addEventListener("pointerdown",N),document.addEventListener("pointerup",N),document.addEventListener("touchmove",N),document.addEventListener("touchstart",N),document.addEventListener("touchend",N)}function oe(){document.removeEventListener("mousemove",N),document.removeEventListener("mousedown",N),document.removeEventListener("mouseup",N),document.removeEventListener("pointermove",N),document.removeEventListener("pointerdown",N),document.removeEventListener("pointerup",N),document.removeEventListener("touchmove",N),document.removeEventListener("touchstart",N),document.removeEventListener("touchend",N)}function N(T){T.target.nodeName&&T.target.nodeName.toLowerCase()==="html"||(n=!1,oe())}document.addEventListener("keydown",p,!0),document.addEventListener("mousedown",m,!0),document.addEventListener("pointerdown",m,!0),document.addEventListener("touchstart",m,!0),document.addEventListener("visibilitychange",v,!0),G(),r.addEventListener("focus",d,!0),r.addEventListener("blur",h,!0),r.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&r.host?r.host.setAttribute("data-js-focus-visible",""):r.nodeType===Node.DOCUMENT_NODE&&(document.documentElement.classList.add("js-focus-visible"),document.documentElement.setAttribute("data-js-focus-visible",""))}if(typeof window!="undefined"&&typeof document!="undefined"){window.applyFocusVisiblePolyfill=e;var t;try{t=new CustomEvent("focus-visible-polyfill-ready")}catch(r){t=document.createEvent("CustomEvent"),t.initCustomEvent("focus-visible-polyfill-ready",!1,!1,{})}window.dispatchEvent(t)}typeof document!="undefined"&&e(document)})});var fn=Ht(Er=>{(function(e){var t=function(){try{return!!Symbol.iterator}catch(f){return!1}},r=t(),n=function(f){var u={next:function(){var p=f.shift();return{done:p===void 0,value:p}}};return r&&(u[Symbol.iterator]=function(){return u}),u},o=function(f){return encodeURIComponent(f).replace(/%20/g,"+")},i=function(f){return decodeURIComponent(String(f).replace(/\+/g," "))},s=function(){var f=function(p){Object.defineProperty(this,"_entries",{writable:!0,value:{}});var m=typeof p;if(m!=="undefined")if(m==="string")p!==""&&this._fromString(p);else if(p instanceof f){var d=this;p.forEach(function(oe,N){d.append(N,oe)})}else if(p!==null&&m==="object")if(Object.prototype.toString.call(p)==="[object Array]")for(var h=0;hd[0]?1:0}),f._entries&&(f._entries={});for(var p=0;p1?i(d[1]):"")}})})(typeof global!="undefined"?global:typeof window!="undefined"?window:typeof self!="undefined"?self:Er);(function(e){var t=function(){try{var o=new e.URL("b","http://a");return o.pathname="c d",o.href==="http://a/c%20d"&&o.searchParams}catch(i){return!1}},r=function(){var o=e.URL,i=function(c,f){typeof c!="string"&&(c=String(c)),f&&typeof f!="string"&&(f=String(f));var u=document,p;if(f&&(e.location===void 0||f!==e.location.href)){f=f.toLowerCase(),u=document.implementation.createHTMLDocument(""),p=u.createElement("base"),p.href=f,u.head.appendChild(p);try{if(p.href.indexOf(f)!==0)throw new Error(p.href)}catch(T){throw new Error("URL unable to set base "+f+" due to "+T)}}var m=u.createElement("a");m.href=c,p&&(u.body.appendChild(m),m.href=m.href);var d=u.createElement("input");if(d.type="url",d.value=c,m.protocol===":"||!/:/.test(m.href)||!d.checkValidity()&&!f)throw new TypeError("Invalid URL");Object.defineProperty(this,"_anchorElement",{value:m});var h=new e.URLSearchParams(this.search),v=!0,G=!0,oe=this;["append","delete","set"].forEach(function(T){var Qe=h[T];h[T]=function(){Qe.apply(h,arguments),v&&(G=!1,oe.search=h.toString(),G=!0)}}),Object.defineProperty(this,"searchParams",{value:h,enumerable:!0});var N=void 0;Object.defineProperty(this,"_updateSearchParams",{enumerable:!1,configurable:!1,writable:!1,value:function(){this.search!==N&&(N=this.search,G&&(v=!1,this.searchParams._fromString(this.search),v=!0))}})},s=i.prototype,a=function(c){Object.defineProperty(s,c,{get:function(){return this._anchorElement[c]},set:function(f){this._anchorElement[c]=f},enumerable:!0})};["hash","host","hostname","port","protocol"].forEach(function(c){a(c)}),Object.defineProperty(s,"search",{get:function(){return this._anchorElement.search},set:function(c){this._anchorElement.search=c,this._updateSearchParams()},enumerable:!0}),Object.defineProperties(s,{toString:{get:function(){var c=this;return function(){return c.href}}},href:{get:function(){return this._anchorElement.href.replace(/\?$/,"")},set:function(c){this._anchorElement.href=c,this._updateSearchParams()},enumerable:!0},pathname:{get:function(){return this._anchorElement.pathname.replace(/(^\/?)/,"/")},set:function(c){this._anchorElement.pathname=c},enumerable:!0},origin:{get:function(){var c={"http:":80,"https:":443,"ftp:":21}[this._anchorElement.protocol],f=this._anchorElement.port!=c&&this._anchorElement.port!=="";return this._anchorElement.protocol+"//"+this._anchorElement.hostname+(f?":"+this._anchorElement.port:"")},enumerable:!0},password:{get:function(){return""},set:function(c){},enumerable:!0},username:{get:function(){return""},set:function(c){},enumerable:!0}}),i.createObjectURL=function(c){return o.createObjectURL.apply(o,arguments)},i.revokeObjectURL=function(c){return o.revokeObjectURL.apply(o,arguments)},e.URL=i};if(t()||r(),e.location!==void 0&&!("origin"in e.location)){var n=function(){return e.location.protocol+"//"+e.location.hostname+(e.location.port?":"+e.location.port:"")};try{Object.defineProperty(e.location,"origin",{get:n,enumerable:!0})}catch(o){setInterval(function(){e.location.origin=n()},100)}}})(typeof global!="undefined"?global:typeof window!="undefined"?window:typeof self!="undefined"?self:Er)});var Kr=Ht((Mt,qr)=>{/*! + * clipboard.js v2.0.11 + * https://clipboardjs.com/ + * + * Licensed MIT © Zeno Rocha + */(function(t,r){typeof Mt=="object"&&typeof qr=="object"?qr.exports=r():typeof define=="function"&&define.amd?define([],r):typeof Mt=="object"?Mt.ClipboardJS=r():t.ClipboardJS=r()})(Mt,function(){return function(){var e={686:function(n,o,i){"use strict";i.d(o,{default:function(){return Ci}});var s=i(279),a=i.n(s),c=i(370),f=i.n(c),u=i(817),p=i.n(u);function m(j){try{return document.execCommand(j)}catch(O){return!1}}var d=function(O){var E=p()(O);return m("cut"),E},h=d;function v(j){var O=document.documentElement.getAttribute("dir")==="rtl",E=document.createElement("textarea");E.style.fontSize="12pt",E.style.border="0",E.style.padding="0",E.style.margin="0",E.style.position="absolute",E.style[O?"right":"left"]="-9999px";var H=window.pageYOffset||document.documentElement.scrollTop;return E.style.top="".concat(H,"px"),E.setAttribute("readonly",""),E.value=j,E}var G=function(O,E){var H=v(O);E.container.appendChild(H);var I=p()(H);return m("copy"),H.remove(),I},oe=function(O){var E=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{container:document.body},H="";return typeof O=="string"?H=G(O,E):O instanceof HTMLInputElement&&!["text","search","url","tel","password"].includes(O==null?void 0:O.type)?H=G(O.value,E):(H=p()(O),m("copy")),H},N=oe;function T(j){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?T=function(E){return typeof E}:T=function(E){return E&&typeof Symbol=="function"&&E.constructor===Symbol&&E!==Symbol.prototype?"symbol":typeof E},T(j)}var Qe=function(){var O=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},E=O.action,H=E===void 0?"copy":E,I=O.container,q=O.target,Me=O.text;if(H!=="copy"&&H!=="cut")throw new Error('Invalid "action" value, use either "copy" or "cut"');if(q!==void 0)if(q&&T(q)==="object"&&q.nodeType===1){if(H==="copy"&&q.hasAttribute("disabled"))throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');if(H==="cut"&&(q.hasAttribute("readonly")||q.hasAttribute("disabled")))throw new Error(`Invalid "target" attribute. You can't cut text from elements with "readonly" or "disabled" attributes`)}else throw new Error('Invalid "target" value, use a valid Element');if(Me)return N(Me,{container:I});if(q)return H==="cut"?h(q):N(q,{container:I})},De=Qe;function $e(j){return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?$e=function(E){return typeof E}:$e=function(E){return E&&typeof Symbol=="function"&&E.constructor===Symbol&&E!==Symbol.prototype?"symbol":typeof E},$e(j)}function wi(j,O){if(!(j instanceof O))throw new TypeError("Cannot call a class as a function")}function rn(j,O){for(var E=0;E0&&arguments[0]!==void 0?arguments[0]:{};this.action=typeof I.action=="function"?I.action:this.defaultAction,this.target=typeof I.target=="function"?I.target:this.defaultTarget,this.text=typeof I.text=="function"?I.text:this.defaultText,this.container=$e(I.container)==="object"?I.container:document.body}},{key:"listenClick",value:function(I){var q=this;this.listener=f()(I,"click",function(Me){return q.onClick(Me)})}},{key:"onClick",value:function(I){var q=I.delegateTarget||I.currentTarget,Me=this.action(q)||"copy",Rt=De({action:Me,container:this.container,target:this.target(q),text:this.text(q)});this.emit(Rt?"success":"error",{action:Me,text:Rt,trigger:q,clearSelection:function(){q&&q.focus(),window.getSelection().removeAllRanges()}})}},{key:"defaultAction",value:function(I){return vr("action",I)}},{key:"defaultTarget",value:function(I){var q=vr("target",I);if(q)return document.querySelector(q)}},{key:"defaultText",value:function(I){return vr("text",I)}},{key:"destroy",value:function(){this.listener.destroy()}}],[{key:"copy",value:function(I){var q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{container:document.body};return N(I,q)}},{key:"cut",value:function(I){return h(I)}},{key:"isSupported",value:function(){var I=arguments.length>0&&arguments[0]!==void 0?arguments[0]:["copy","cut"],q=typeof I=="string"?[I]:I,Me=!!document.queryCommandSupported;return q.forEach(function(Rt){Me=Me&&!!document.queryCommandSupported(Rt)}),Me}}]),E}(a()),Ci=Ai},828:function(n){var o=9;if(typeof Element!="undefined"&&!Element.prototype.matches){var i=Element.prototype;i.matches=i.matchesSelector||i.mozMatchesSelector||i.msMatchesSelector||i.oMatchesSelector||i.webkitMatchesSelector}function s(a,c){for(;a&&a.nodeType!==o;){if(typeof a.matches=="function"&&a.matches(c))return a;a=a.parentNode}}n.exports=s},438:function(n,o,i){var s=i(828);function a(u,p,m,d,h){var v=f.apply(this,arguments);return u.addEventListener(m,v,h),{destroy:function(){u.removeEventListener(m,v,h)}}}function c(u,p,m,d,h){return typeof u.addEventListener=="function"?a.apply(null,arguments):typeof m=="function"?a.bind(null,document).apply(null,arguments):(typeof u=="string"&&(u=document.querySelectorAll(u)),Array.prototype.map.call(u,function(v){return a(v,p,m,d,h)}))}function f(u,p,m,d){return function(h){h.delegateTarget=s(h.target,p),h.delegateTarget&&d.call(u,h)}}n.exports=c},879:function(n,o){o.node=function(i){return i!==void 0&&i instanceof HTMLElement&&i.nodeType===1},o.nodeList=function(i){var s=Object.prototype.toString.call(i);return i!==void 0&&(s==="[object NodeList]"||s==="[object HTMLCollection]")&&"length"in i&&(i.length===0||o.node(i[0]))},o.string=function(i){return typeof i=="string"||i instanceof String},o.fn=function(i){var s=Object.prototype.toString.call(i);return s==="[object Function]"}},370:function(n,o,i){var s=i(879),a=i(438);function c(m,d,h){if(!m&&!d&&!h)throw new Error("Missing required arguments");if(!s.string(d))throw new TypeError("Second argument must be a String");if(!s.fn(h))throw new TypeError("Third argument must be a Function");if(s.node(m))return f(m,d,h);if(s.nodeList(m))return u(m,d,h);if(s.string(m))return p(m,d,h);throw new TypeError("First argument must be a String, HTMLElement, HTMLCollection, or NodeList")}function f(m,d,h){return m.addEventListener(d,h),{destroy:function(){m.removeEventListener(d,h)}}}function u(m,d,h){return Array.prototype.forEach.call(m,function(v){v.addEventListener(d,h)}),{destroy:function(){Array.prototype.forEach.call(m,function(v){v.removeEventListener(d,h)})}}}function p(m,d,h){return a(document.body,m,d,h)}n.exports=c},817:function(n){function o(i){var s;if(i.nodeName==="SELECT")i.focus(),s=i.value;else if(i.nodeName==="INPUT"||i.nodeName==="TEXTAREA"){var a=i.hasAttribute("readonly");a||i.setAttribute("readonly",""),i.select(),i.setSelectionRange(0,i.value.length),a||i.removeAttribute("readonly"),s=i.value}else{i.hasAttribute("contenteditable")&&i.focus();var c=window.getSelection(),f=document.createRange();f.selectNodeContents(i),c.removeAllRanges(),c.addRange(f),s=c.toString()}return s}n.exports=o},279:function(n){function o(){}o.prototype={on:function(i,s,a){var c=this.e||(this.e={});return(c[i]||(c[i]=[])).push({fn:s,ctx:a}),this},once:function(i,s,a){var c=this;function f(){c.off(i,f),s.apply(a,arguments)}return f._=s,this.on(i,f,a)},emit:function(i){var s=[].slice.call(arguments,1),a=((this.e||(this.e={}))[i]||[]).slice(),c=0,f=a.length;for(c;c{"use strict";/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */var ns=/["'&<>]/;Go.exports=os;function os(e){var t=""+e,r=ns.exec(t);if(!r)return t;var n,o="",i=0,s=0;for(i=r.index;i0&&i[i.length-1])&&(f[0]===6||f[0]===2)){r=0;continue}if(f[0]===3&&(!i||f[1]>i[0]&&f[1]=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function W(e,t){var r=typeof Symbol=="function"&&e[Symbol.iterator];if(!r)return e;var n=r.call(e),o,i=[],s;try{for(;(t===void 0||t-- >0)&&!(o=n.next()).done;)i.push(o.value)}catch(a){s={error:a}}finally{try{o&&!o.done&&(r=n.return)&&r.call(n)}finally{if(s)throw s.error}}return i}function D(e,t,r){if(r||arguments.length===2)for(var n=0,o=t.length,i;n1||a(m,d)})})}function a(m,d){try{c(n[m](d))}catch(h){p(i[0][3],h)}}function c(m){m.value instanceof et?Promise.resolve(m.value.v).then(f,u):p(i[0][2],m)}function f(m){a("next",m)}function u(m){a("throw",m)}function p(m,d){m(d),i.shift(),i.length&&a(i[0][0],i[0][1])}}function ln(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],r;return t?t.call(e):(e=typeof Ee=="function"?Ee(e):e[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(i){r[i]=e[i]&&function(s){return new Promise(function(a,c){s=e[i](s),o(a,c,s.done,s.value)})}}function o(i,s,a,c){Promise.resolve(c).then(function(f){i({value:f,done:a})},s)}}function A(e){return typeof e=="function"}function at(e){var t=function(n){Error.call(n),n.stack=new Error().stack},r=e(t);return r.prototype=Object.create(Error.prototype),r.prototype.constructor=r,r}var $t=at(function(e){return function(r){e(this),this.message=r?r.length+` errors occurred during unsubscription: +`+r.map(function(n,o){return o+1+") "+n.toString()}).join(` + `):"",this.name="UnsubscriptionError",this.errors=r}});function Ve(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var Ie=function(){function e(t){this.initialTeardown=t,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var t,r,n,o,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var a=Ee(s),c=a.next();!c.done;c=a.next()){var f=c.value;f.remove(this)}}catch(v){t={error:v}}finally{try{c&&!c.done&&(r=a.return)&&r.call(a)}finally{if(t)throw t.error}}else s.remove(this);var u=this.initialTeardown;if(A(u))try{u()}catch(v){i=v instanceof $t?v.errors:[v]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var m=Ee(p),d=m.next();!d.done;d=m.next()){var h=d.value;try{mn(h)}catch(v){i=i!=null?i:[],v instanceof $t?i=D(D([],W(i)),W(v.errors)):i.push(v)}}}catch(v){n={error:v}}finally{try{d&&!d.done&&(o=m.return)&&o.call(m)}finally{if(n)throw n.error}}}if(i)throw new $t(i)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)mn(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=(r=this._finalizers)!==null&&r!==void 0?r:[]).push(t)}},e.prototype._hasParent=function(t){var r=this._parentage;return r===t||Array.isArray(r)&&r.includes(t)},e.prototype._addParent=function(t){var r=this._parentage;this._parentage=Array.isArray(r)?(r.push(t),r):r?[r,t]:t},e.prototype._removeParent=function(t){var r=this._parentage;r===t?this._parentage=null:Array.isArray(r)&&Ve(r,t)},e.prototype.remove=function(t){var r=this._finalizers;r&&Ve(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=function(){var t=new e;return t.closed=!0,t}(),e}();var Sr=Ie.EMPTY;function It(e){return e instanceof Ie||e&&"closed"in e&&A(e.remove)&&A(e.add)&&A(e.unsubscribe)}function mn(e){A(e)?e():e.unsubscribe()}var Le={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var st={setTimeout:function(e,t){for(var r=[],n=2;n0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(r){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,r)},t.prototype._subscribe=function(r){return this._throwIfClosed(),this._checkFinalizedStatuses(r),this._innerSubscribe(r)},t.prototype._innerSubscribe=function(r){var n=this,o=this,i=o.hasError,s=o.isStopped,a=o.observers;return i||s?Sr:(this.currentObservers=null,a.push(r),new Ie(function(){n.currentObservers=null,Ve(a,r)}))},t.prototype._checkFinalizedStatuses=function(r){var n=this,o=n.hasError,i=n.thrownError,s=n.isStopped;o?r.error(i):s&&r.complete()},t.prototype.asObservable=function(){var r=new F;return r.source=this,r},t.create=function(r,n){return new En(r,n)},t}(F);var En=function(e){ie(t,e);function t(r,n){var o=e.call(this)||this;return o.destination=r,o.source=n,o}return t.prototype.next=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.next)===null||o===void 0||o.call(n,r)},t.prototype.error=function(r){var n,o;(o=(n=this.destination)===null||n===void 0?void 0:n.error)===null||o===void 0||o.call(n,r)},t.prototype.complete=function(){var r,n;(n=(r=this.destination)===null||r===void 0?void 0:r.complete)===null||n===void 0||n.call(r)},t.prototype._subscribe=function(r){var n,o;return(o=(n=this.source)===null||n===void 0?void 0:n.subscribe(r))!==null&&o!==void 0?o:Sr},t}(x);var Et={now:function(){return(Et.delegate||Date).now()},delegate:void 0};var wt=function(e){ie(t,e);function t(r,n,o){r===void 0&&(r=1/0),n===void 0&&(n=1/0),o===void 0&&(o=Et);var i=e.call(this)||this;return i._bufferSize=r,i._windowTime=n,i._timestampProvider=o,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=n===1/0,i._bufferSize=Math.max(1,r),i._windowTime=Math.max(1,n),i}return t.prototype.next=function(r){var n=this,o=n.isStopped,i=n._buffer,s=n._infiniteTimeWindow,a=n._timestampProvider,c=n._windowTime;o||(i.push(r),!s&&i.push(a.now()+c)),this._trimBuffer(),e.prototype.next.call(this,r)},t.prototype._subscribe=function(r){this._throwIfClosed(),this._trimBuffer();for(var n=this._innerSubscribe(r),o=this,i=o._infiniteTimeWindow,s=o._buffer,a=s.slice(),c=0;c0?e.prototype.requestAsyncId.call(this,r,n,o):(r.actions.push(this),r._scheduled||(r._scheduled=ut.requestAnimationFrame(function(){return r.flush(void 0)})))},t.prototype.recycleAsyncId=function(r,n,o){var i;if(o===void 0&&(o=0),o!=null?o>0:this.delay>0)return e.prototype.recycleAsyncId.call(this,r,n,o);var s=r.actions;n!=null&&((i=s[s.length-1])===null||i===void 0?void 0:i.id)!==n&&(ut.cancelAnimationFrame(n),r._scheduled=void 0)},t}(Ut);var Tn=function(e){ie(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.flush=function(r){this._active=!0;var n=this._scheduled;this._scheduled=void 0;var o=this.actions,i;r=r||o.shift();do if(i=r.execute(r.state,r.delay))break;while((r=o[0])&&r.id===n&&o.shift());if(this._active=!1,i){for(;(r=o[0])&&r.id===n&&o.shift();)r.unsubscribe();throw i}},t}(Wt);var Te=new Tn(Sn);var _=new F(function(e){return e.complete()});function Dt(e){return e&&A(e.schedule)}function Cr(e){return e[e.length-1]}function Ye(e){return A(Cr(e))?e.pop():void 0}function Oe(e){return Dt(Cr(e))?e.pop():void 0}function Vt(e,t){return typeof Cr(e)=="number"?e.pop():t}var pt=function(e){return e&&typeof e.length=="number"&&typeof e!="function"};function zt(e){return A(e==null?void 0:e.then)}function Nt(e){return A(e[ft])}function qt(e){return Symbol.asyncIterator&&A(e==null?void 0:e[Symbol.asyncIterator])}function Kt(e){return new TypeError("You provided "+(e!==null&&typeof e=="object"?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}function Ni(){return typeof Symbol!="function"||!Symbol.iterator?"@@iterator":Symbol.iterator}var Qt=Ni();function Yt(e){return A(e==null?void 0:e[Qt])}function Gt(e){return pn(this,arguments,function(){var r,n,o,i;return Pt(this,function(s){switch(s.label){case 0:r=e.getReader(),s.label=1;case 1:s.trys.push([1,,9,10]),s.label=2;case 2:return[4,et(r.read())];case 3:return n=s.sent(),o=n.value,i=n.done,i?[4,et(void 0)]:[3,5];case 4:return[2,s.sent()];case 5:return[4,et(o)];case 6:return[4,s.sent()];case 7:return s.sent(),[3,2];case 8:return[3,10];case 9:return r.releaseLock(),[7];case 10:return[2]}})})}function Bt(e){return A(e==null?void 0:e.getReader)}function U(e){if(e instanceof F)return e;if(e!=null){if(Nt(e))return qi(e);if(pt(e))return Ki(e);if(zt(e))return Qi(e);if(qt(e))return On(e);if(Yt(e))return Yi(e);if(Bt(e))return Gi(e)}throw Kt(e)}function qi(e){return new F(function(t){var r=e[ft]();if(A(r.subscribe))return r.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function Ki(e){return new F(function(t){for(var r=0;r=2;return function(n){return n.pipe(e?L(function(o,i){return e(o,i,n)}):de,ge(1),r?He(t):Vn(function(){return new Xt}))}}function zn(){for(var e=[],t=0;t=2,!0))}function pe(e){e===void 0&&(e={});var t=e.connector,r=t===void 0?function(){return new x}:t,n=e.resetOnError,o=n===void 0?!0:n,i=e.resetOnComplete,s=i===void 0?!0:i,a=e.resetOnRefCountZero,c=a===void 0?!0:a;return function(f){var u,p,m,d=0,h=!1,v=!1,G=function(){p==null||p.unsubscribe(),p=void 0},oe=function(){G(),u=m=void 0,h=v=!1},N=function(){var T=u;oe(),T==null||T.unsubscribe()};return y(function(T,Qe){d++,!v&&!h&&G();var De=m=m!=null?m:r();Qe.add(function(){d--,d===0&&!v&&!h&&(p=$r(N,c))}),De.subscribe(Qe),!u&&d>0&&(u=new rt({next:function($e){return De.next($e)},error:function($e){v=!0,G(),p=$r(oe,o,$e),De.error($e)},complete:function(){h=!0,G(),p=$r(oe,s),De.complete()}}),U(T).subscribe(u))})(f)}}function $r(e,t){for(var r=[],n=2;ne.next(document)),e}function K(e,t=document){return Array.from(t.querySelectorAll(e))}function z(e,t=document){let r=ce(e,t);if(typeof r=="undefined")throw new ReferenceError(`Missing element: expected "${e}" to be present`);return r}function ce(e,t=document){return t.querySelector(e)||void 0}function _e(){return document.activeElement instanceof HTMLElement&&document.activeElement||void 0}function er(e){return C(b(document.body,"focusin"),b(document.body,"focusout")).pipe(ke(1),l(()=>{let t=_e();return typeof t!="undefined"?e.contains(t):!1}),V(e===_e()),B())}function Xe(e){return{x:e.offsetLeft,y:e.offsetTop}}function Qn(e){return C(b(window,"load"),b(window,"resize")).pipe(Ce(0,Te),l(()=>Xe(e)),V(Xe(e)))}function tr(e){return{x:e.scrollLeft,y:e.scrollTop}}function dt(e){return C(b(e,"scroll"),b(window,"resize")).pipe(Ce(0,Te),l(()=>tr(e)),V(tr(e)))}var Gn=function(){if(typeof Map!="undefined")return Map;function e(t,r){var n=-1;return t.some(function(o,i){return o[0]===r?(n=i,!0):!1}),n}return function(){function t(){this.__entries__=[]}return Object.defineProperty(t.prototype,"size",{get:function(){return this.__entries__.length},enumerable:!0,configurable:!0}),t.prototype.get=function(r){var n=e(this.__entries__,r),o=this.__entries__[n];return o&&o[1]},t.prototype.set=function(r,n){var o=e(this.__entries__,r);~o?this.__entries__[o][1]=n:this.__entries__.push([r,n])},t.prototype.delete=function(r){var n=this.__entries__,o=e(n,r);~o&&n.splice(o,1)},t.prototype.has=function(r){return!!~e(this.__entries__,r)},t.prototype.clear=function(){this.__entries__.splice(0)},t.prototype.forEach=function(r,n){n===void 0&&(n=null);for(var o=0,i=this.__entries__;o0},e.prototype.connect_=function(){!Dr||this.connected_||(document.addEventListener("transitionend",this.onTransitionEnd_),window.addEventListener("resize",this.refresh),ga?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener("DOMSubtreeModified",this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},e.prototype.disconnect_=function(){!Dr||!this.connected_||(document.removeEventListener("transitionend",this.onTransitionEnd_),window.removeEventListener("resize",this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener("DOMSubtreeModified",this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},e.prototype.onTransitionEnd_=function(t){var r=t.propertyName,n=r===void 0?"":r,o=va.some(function(i){return!!~n.indexOf(i)});o&&this.refresh()},e.getInstance=function(){return this.instance_||(this.instance_=new e),this.instance_},e.instance_=null,e}(),Bn=function(e,t){for(var r=0,n=Object.keys(t);r0},e}(),Xn=typeof WeakMap!="undefined"?new WeakMap:new Gn,Zn=function(){function e(t){if(!(this instanceof e))throw new TypeError("Cannot call a class as a function.");if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");var r=ya.getInstance(),n=new Aa(t,r,this);Xn.set(this,n)}return e}();["observe","unobserve","disconnect"].forEach(function(e){Zn.prototype[e]=function(){var t;return(t=Xn.get(this))[e].apply(t,arguments)}});var Ca=function(){return typeof rr.ResizeObserver!="undefined"?rr.ResizeObserver:Zn}(),eo=Ca;var to=new x,Ra=$(()=>k(new eo(e=>{for(let t of e)to.next(t)}))).pipe(g(e=>C(ze,k(e)).pipe(R(()=>e.disconnect()))),J(1));function he(e){return{width:e.offsetWidth,height:e.offsetHeight}}function ye(e){return Ra.pipe(S(t=>t.observe(e)),g(t=>to.pipe(L(({target:r})=>r===e),R(()=>t.unobserve(e)),l(()=>he(e)))),V(he(e)))}function bt(e){return{width:e.scrollWidth,height:e.scrollHeight}}function ir(e){let t=e.parentElement;for(;t&&(e.scrollWidth<=t.scrollWidth&&e.scrollHeight<=t.scrollHeight);)t=(e=t).parentElement;return t?e:void 0}var ro=new x,ka=$(()=>k(new IntersectionObserver(e=>{for(let t of e)ro.next(t)},{threshold:0}))).pipe(g(e=>C(ze,k(e)).pipe(R(()=>e.disconnect()))),J(1));function ar(e){return ka.pipe(S(t=>t.observe(e)),g(t=>ro.pipe(L(({target:r})=>r===e),R(()=>t.unobserve(e)),l(({isIntersecting:r})=>r))))}function no(e,t=16){return dt(e).pipe(l(({y:r})=>{let n=he(e),o=bt(e);return r>=o.height-n.height-t}),B())}var sr={drawer:z("[data-md-toggle=drawer]"),search:z("[data-md-toggle=search]")};function oo(e){return sr[e].checked}function Ke(e,t){sr[e].checked!==t&&sr[e].click()}function Ue(e){let t=sr[e];return b(t,"change").pipe(l(()=>t.checked),V(t.checked))}function Ha(e,t){switch(e.constructor){case HTMLInputElement:return e.type==="radio"?/^Arrow/.test(t):!0;case HTMLSelectElement:case HTMLTextAreaElement:return!0;default:return e.isContentEditable}}function Pa(){return C(b(window,"compositionstart").pipe(l(()=>!0)),b(window,"compositionend").pipe(l(()=>!1))).pipe(V(!1))}function io(){let e=b(window,"keydown").pipe(L(t=>!(t.metaKey||t.ctrlKey)),l(t=>({mode:oo("search")?"search":"global",type:t.key,claim(){t.preventDefault(),t.stopPropagation()}})),L(({mode:t,type:r})=>{if(t==="global"){let n=_e();if(typeof n!="undefined")return!Ha(n,r)}return!0}),pe());return Pa().pipe(g(t=>t?_:e))}function le(){return new URL(location.href)}function ot(e){location.href=e.href}function ao(){return new x}function so(e,t){if(typeof t=="string"||typeof t=="number")e.innerHTML+=t.toString();else if(t instanceof Node)e.appendChild(t);else if(Array.isArray(t))for(let r of t)so(e,r)}function M(e,t,...r){let n=document.createElement(e);if(t)for(let o of Object.keys(t))typeof t[o]!="undefined"&&(typeof t[o]!="boolean"?n.setAttribute(o,t[o]):n.setAttribute(o,""));for(let o of r)so(n,o);return n}function cr(e){if(e>999){let t=+((e-950)%1e3>99);return`${((e+1e-6)/1e3).toFixed(t)}k`}else return e.toString()}function co(){return location.hash.substring(1)}function Vr(e){let t=M("a",{href:e});t.addEventListener("click",r=>r.stopPropagation()),t.click()}function $a(){return b(window,"hashchange").pipe(l(co),V(co()),L(e=>e.length>0),J(1))}function fo(){return $a().pipe(l(e=>ce(`[id="${e}"]`)),L(e=>typeof e!="undefined"))}function zr(e){let t=matchMedia(e);return Zt(r=>t.addListener(()=>r(t.matches))).pipe(V(t.matches))}function uo(){let e=matchMedia("print");return C(b(window,"beforeprint").pipe(l(()=>!0)),b(window,"afterprint").pipe(l(()=>!1))).pipe(V(e.matches))}function Nr(e,t){return e.pipe(g(r=>r?t():_))}function fr(e,t={credentials:"same-origin"}){return ue(fetch(`${e}`,t)).pipe(fe(()=>_),g(r=>r.status!==200?Tt(()=>new Error(r.statusText)):k(r)))}function We(e,t){return fr(e,t).pipe(g(r=>r.json()),J(1))}function po(e,t){let r=new DOMParser;return fr(e,t).pipe(g(n=>n.text()),l(n=>r.parseFromString(n,"text/xml")),J(1))}function ur(e){let t=M("script",{src:e});return $(()=>(document.head.appendChild(t),C(b(t,"load"),b(t,"error").pipe(g(()=>Tt(()=>new ReferenceError(`Invalid script: ${e}`))))).pipe(l(()=>{}),R(()=>document.head.removeChild(t)),ge(1))))}function lo(){return{x:Math.max(0,scrollX),y:Math.max(0,scrollY)}}function mo(){return C(b(window,"scroll",{passive:!0}),b(window,"resize",{passive:!0})).pipe(l(lo),V(lo()))}function ho(){return{width:innerWidth,height:innerHeight}}function bo(){return b(window,"resize",{passive:!0}).pipe(l(ho),V(ho()))}function vo(){return Q([mo(),bo()]).pipe(l(([e,t])=>({offset:e,size:t})),J(1))}function pr(e,{viewport$:t,header$:r}){let n=t.pipe(Z("size")),o=Q([n,r]).pipe(l(()=>Xe(e)));return Q([r,t,o]).pipe(l(([{height:i},{offset:s,size:a},{x:c,y:f}])=>({offset:{x:s.x-c,y:s.y-f+i},size:a})))}(()=>{function e(n,o){parent.postMessage(n,o||"*")}function t(...n){return n.reduce((o,i)=>o.then(()=>new Promise(s=>{let a=document.createElement("script");a.src=i,a.onload=s,document.body.appendChild(a)})),Promise.resolve())}var r=class extends EventTarget{constructor(n){super(),this.url=n,this.m=i=>{i.source===this.w&&(this.dispatchEvent(new MessageEvent("message",{data:i.data})),this.onmessage&&this.onmessage(i))},this.e=(i,s,a,c,f)=>{if(s===`${this.url}`){let u=new ErrorEvent("error",{message:i,filename:s,lineno:a,colno:c,error:f});this.dispatchEvent(u),this.onerror&&this.onerror(u)}};let o=document.createElement("iframe");o.hidden=!0,document.body.appendChild(this.iframe=o),this.w.document.open(),this.w.document.write(` + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + +

Machine-oriented binary syntax

+ + +
+ + + +
+ +

The preserves.binary module implements the Preserves machine-oriented binary +syntax.

+

The main entry points are functions encode, +canonicalize, decode, and +decode_with_annotations.

+
>>> encode(Record(Symbol('hi'), []))
+b'\xb4\xb3\x02hi\x84'
+>>> decode(b'\xb4\xb3\x02hi\x84')
+#hi()
+
+ + + +
+ + + + + + + + +
+ + + +

+Decoder(packet=b'', include_annotations=False, decode_embedded=lambda x: x) + +

+ + +
+

+ Bases: BinaryCodec

+ + +

Implementation of a decoder for the machine-oriented binary Preserves syntax.

+ +

Parameters:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescriptionDefault
packet + bytes +

initial contents of the input buffer; may subsequently be extended by calling +extend.

+ b'' +
include_annotations + bool +

if True, wrap each value and subvalue in an +Annotated object.

+ False +
decode_embedded +

function accepting a Value and returning a possibly-decoded form of that value +suitable for placing into an Embedded object.

+ lambda x: x +
+

Normal usage is to supply a buffer, and keep calling next +until a ShortPacket exception is raised:

+
>>> d = Decoder(b'\xb0\x01{\xb1\x05hello\x85\xb3\x01x\xb5\x84')
+>>> d.next()
+123
+>>> d.next()
+'hello'
+>>> d.next()
+()
+>>> d.next()
+Traceback (most recent call last):
+  ...
+preserves.error.ShortPacket: Short packet
+
+

Alternatively, keep calling try_next until it yields +None, which is not in the domain of Preserves Values:

+
>>> d = Decoder(b'\xb0\x01{\xb1\x05hello\x85\xb3\x01x\xb5\x84')
+>>> d.try_next()
+123
+>>> d.try_next()
+'hello'
+>>> d.try_next()
+()
+>>> d.try_next()
+
+

For convenience, Decoder implements the iterator interface, +backing it with try_next, so you can simply iterate +over all complete values in an input:

+
>>> d = Decoder(b'\xb0\x01{\xb1\x05hello\x85\xb3\x01x\xb5\x84')
+>>> list(d)
+[123, 'hello', ()]
+
+
>>> for v in Decoder(b'\xb0\x01{\xb1\x05hello\x85\xb3\x01x\xb5\x84'):
+...     print(repr(v))
+123
+'hello'
+()
+
+

Supply include_annotations=True to read annotations alongside the annotated values:

+
>>> d = Decoder(b'\xb0\x01{\xb1\x05hello\x85\xb3\x01x\xb5\x84', include_annotations=True)
+>>> list(d)
+[123, 'hello', @#x ()]
+
+

If you are incrementally reading from, say, a socket, you can use +extend to add new input as if comes available:

+
>>> d = Decoder(b'\xb0\x01{\xb1\x05he')
+>>> d.try_next()
+123
+>>> d.try_next() # returns None because the input is incomplete
+>>> d.extend(b'llo')
+>>> d.try_next()
+'hello'
+>>> d.try_next()
+
+ +

Attributes:

+ + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
packet + bytes +

buffered input waiting to be processed

index + int +

read position within packet

+ + +
+ Source code in preserves/binary.py +
127
+128
+129
+130
+131
+132
def __init__(self, packet=b'', include_annotations=False, decode_embedded=lambda x: x):
+    super(Decoder, self).__init__()
+    self.packet = packet
+    self.index = 0
+    self.include_annotations = include_annotations
+    self.decode_embedded = decode_embedded
+
+
+ + + +
+ + + + + + + + + +
+ + + +

+extend(data) + +

+ + +
+ +

Appends data to the remaining bytes in self.packet, trimming already-processed +bytes from the front of self.packet and resetting self.index to zero.

+ +
+ Source code in preserves/binary.py +
134
+135
+136
+137
+138
def extend(self, data):
+    """Appends `data` to the remaining bytes in `self.packet`, trimming already-processed
+    bytes from the front of `self.packet` and resetting `self.index` to zero."""
+    self.packet = self.packet[self.index:] + data
+    self.index = 0
+
+
+
+ +
+ +
+ + + +

+next() + +

+ + +
+ +

Reads the next complete Value from the internal buffer, raising +ShortPacket if too few bytes are available, or +DecodeError if the input is invalid somehow.

+ +
+ Source code in preserves/binary.py +
189
+190
+191
+192
+193
+194
+195
+196
+197
+198
+199
+200
+201
+202
+203
+204
+205
+206
+207
+208
+209
+210
+211
+212
+213
+214
+215
+216
+217
+218
+219
+220
+221
+222
+223
def next(self):
+    """Reads the next complete `Value` from the internal buffer, raising
+    [ShortPacket][preserves.error.ShortPacket] if too few bytes are available, or
+    [DecodeError][preserves.error.DecodeError] if the input is invalid somehow.
+
+    """
+    tag = self.nextbyte()
+    if tag == 0x80: return self.wrap(False)
+    if tag == 0x81: return self.wrap(True)
+    if tag == 0x84: raise DecodeError('Unexpected end-of-stream marker')
+    if tag == 0x85:
+        a = self.next()
+        v = self.next()
+        return self.unshift_annotation(a, v)
+    if tag == 0x86:
+        if self.decode_embedded is None:
+            raise DecodeError('No decode_embedded function supplied')
+        return self.wrap(Embedded(self.decode_embedded(self.next())))
+    if tag == 0x87:
+        count = self.nextbyte()
+        if count == 4: return self.wrap(Float.from_bytes(self.nextbytes(4)))
+        if count == 8: return self.wrap(struct.unpack('>d', self.nextbytes(8))[0])
+        raise DecodeError('Invalid IEEE754 size')
+    if tag == 0xb0: return self.wrap(self.nextint(self.varint()))
+    if tag == 0xb1: return self.wrap(self.nextbytes(self.varint()).decode('utf-8'))
+    if tag == 0xb2: return self.wrap(self.nextbytes(self.varint()))
+    if tag == 0xb3: return self.wrap(Symbol(self.nextbytes(self.varint()).decode('utf-8')))
+    if tag == 0xb4:
+        vs = self.nextvalues()
+        if not vs: raise DecodeError('Too few elements in encoded record')
+        return self.wrap(Record(vs[0], vs[1:]))
+    if tag == 0xb5: return self.wrap(tuple(self.nextvalues()))
+    if tag == 0xb6: return self.wrap(frozenset(self.nextvalues()))
+    if tag == 0xb7: return self.wrap(ImmutableDict.from_kvs(self.nextvalues()))
+    raise DecodeError('Invalid tag: ' + hex(tag))
+
+
+
+ +
+ +
+ + + +

+try_next() + +

+ + +
+ +

Like next, but returns None instead of raising +ShortPacket.

+ +
+ Source code in preserves/binary.py +
225
+226
+227
+228
+229
+230
+231
+232
+233
def try_next(self):
+    """Like [next][preserves.binary.Decoder.next], but returns `None` instead of raising
+    [ShortPacket][preserves.error.ShortPacket]."""
+    start = self.index
+    try:
+        return self.next()
+    except ShortPacket:
+        self.index = start
+        return None
+
+
+
+ +
+ + + +
+ +
+ +
+ +
+ + + +

+Encoder(encode_embedded=lambda x: x, canonicalize=False, include_annotations=None) + +

+ + +
+

+ Bases: BinaryCodec

+ + +

Implementation of an encoder for the machine-oriented binary Preserves syntax.

+
>>> e = Encoder()
+>>> e.append(123)
+>>> e.append('hello')
+>>> e.append(annotate([], Symbol('x')))
+>>> e.contents()
+b'\xb0\x01{\xb1\x05hello\x85\xb3\x01x\xb5\x84'
+
+ +

Parameters:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescriptionDefault
encode_embedded +

function accepting an Embedded.embeddedValue and +returning a Value for serialization.

+ lambda x: x +
canonicalize + bool +

if True, ensures the serialized data are in canonical +form. This is slightly more work than +producing potentially-non-canonical output.

+ False +
include_annotations + bool | None +

if None, includes annotations in the output only when canonicalize is False, +because canonical serialization of values demands omission of +annotations. If explicitly True or +False, however, annotations will be included resp. excluded no matter the +canonicalize setting. This can be used to get canonical ordering +(canonicalize=True) and annotations (include_annotations=True).

+ None +
+ +

Attributes:

+ + + + + + + + + + + + + + + +
NameTypeDescription
buffer + bytearray +

accumulator for the output of the encoder

+ + +
+ Source code in preserves/binary.py +
295
+296
+297
+298
+299
+300
+301
+302
+303
+304
+305
+306
def __init__(self,
+             encode_embedded=lambda x: x,
+             canonicalize=False,
+             include_annotations=None):
+    super(Encoder, self).__init__()
+    self.buffer = bytearray()
+    self._encode_embedded = encode_embedded
+    self._canonicalize = canonicalize
+    if include_annotations is None:
+        self.include_annotations = not self._canonicalize
+    else:
+        self.include_annotations = include_annotations
+
+
+ + + +
+ + + + + + + + + +
+ + + +

+append(v) + +

+ + +
+ +

Extend self.buffer with an encoding of v.

+ +
+ Source code in preserves/binary.py +
368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
+402
+403
+404
+405
def append(self, v):
+    """Extend `self.buffer` with an encoding of `v`."""
+    v = preserve(v)
+    if hasattr(v, '__preserve_write_binary__'):
+        v.__preserve_write_binary__(self)
+    elif v is False:
+        self.buffer.append(0x80)
+    elif v is True:
+        self.buffer.append(0x81)
+    elif isinstance(v, float):
+        self.buffer.append(0x87)
+        self.buffer.append(8)
+        self.buffer.extend(struct.pack('>d', v))
+    elif isinstance(v, numbers.Number):
+        self.encodeint(v)
+    elif isinstance(v, bytes):
+        self.encodebytes(0xb2, v)
+    elif isinstance(v, basestring_):
+        self.encodebytes(0xb1, v.encode('utf-8'))
+    elif isinstance(v, list):
+        self.encodevalues(0xb5, v)
+    elif isinstance(v, tuple):
+        self.encodevalues(0xb5, v)
+    elif isinstance(v, set):
+        self.encodeset(v)
+    elif isinstance(v, frozenset):
+        self.encodeset(v)
+    elif isinstance(v, dict):
+        self.encodedict(v)
+    else:
+        try:
+            i = iter(v)
+        except TypeError:
+            i = None
+        if i is None:
+            self.cannot_encode(v)
+        else:
+            self.encodevalues(0xb5, i)
+
+
+
+ +
+ +
+ + + +

+contents() + +

+ + +
+ +

Returns a bytes constructed from the contents of self.buffer.

+ +
+ Source code in preserves/binary.py +
317
+318
+319
def contents(self):
+    """Returns a `bytes` constructed from the contents of `self.buffer`."""
+    return bytes(self.buffer)
+
+
+
+ +
+ +
+ + + +

+reset() + +

+ + +
+ +

Clears self.buffer to a fresh empty bytearray.

+ +
+ Source code in preserves/binary.py +
308
+309
+310
def reset(self):
+    """Clears `self.buffer` to a fresh empty `bytearray`."""
+    self.buffer = bytearray()
+
+
+
+ +
+ + + +
+ +
+ +
+ + +
+ + + +

+canonicalize(v, **kwargs) + +

+ + +
+ +

As encode, but sets canonicalize=True in the +Encoder constructor.

+ +
+ Source code in preserves/binary.py +
433
+434
+435
+436
+437
+438
def canonicalize(v, **kwargs):
+    """As [encode][preserves.binary.encode], but sets `canonicalize=True` in the
+    [Encoder][preserves.binary.Encoder] constructor.
+
+    """
+    return encode(v, canonicalize=True, **kwargs)
+
+
+
+ +
+ +
+ + + +

+decode(bs, **kwargs) + +

+ + +
+ +

Yields the first complete encoded value from bs, passing kwargs through to the +Decoder constructor. Raises exceptions as per +next.

+ +

Parameters:

+ + + + + + + + + + + + + + + + + +
NameTypeDescriptionDefault
bs + bytes +

encoded data to decode

+ required +
+ +
+ Source code in preserves/binary.py +
244
+245
+246
+247
+248
+249
+250
+251
+252
+253
def decode(bs, **kwargs):
+    """Yields the first complete encoded value from `bs`, passing `kwargs` through to the
+    [Decoder][preserves.binary.Decoder] constructor. Raises exceptions as per
+    [next][preserves.binary.Decoder.next].
+
+    Args:
+        bs (bytes): encoded data to decode
+
+    """
+    return Decoder(packet=bs, **kwargs).next()
+
+
+
+ +
+ +
+ + + +

+decode_with_annotations(bs, **kwargs) + +

+ + +
+ +

Like decode, but supplying include_annotations=True to the +Decoder constructor.

+ +
+ Source code in preserves/binary.py +
255
+256
+257
+258
def decode_with_annotations(bs, **kwargs):
+    """Like [decode][preserves.binary.decode], but supplying `include_annotations=True` to the
+    [Decoder][preserves.binary.Decoder] constructor."""
+    return Decoder(packet=bs, include_annotations=True, **kwargs).next()
+
+
+
+ +
+ +
+ + + +

+encode(v, **kwargs) + +

+ + +
+ +

Encode a single Value v to a byte string. Any supplied kwargs are passed on to the +underlying Encoder constructor.

+ +
+ Source code in preserves/binary.py +
426
+427
+428
+429
+430
+431
def encode(v, **kwargs):
+    """Encode a single `Value` `v` to a byte string. Any supplied `kwargs` are passed on to the
+    underlying [Encoder][preserves.binary.Encoder] constructor."""
+    e = Encoder(**kwargs)
+    e.append(v)
+    return e.contents()
+
+
+
+ +
+ + + +
+ +
+ +
+ +
+
+ + + Last update: + March 16, 2023 + +
+ Created: + March 16, 2023 + + +
+
+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/python/0.992.0/compare/index.html b/python/0.992.0/compare/index.html new file mode 100644 index 0000000..1b5d5d4 --- /dev/null +++ b/python/0.992.0/compare/index.html @@ -0,0 +1,858 @@ + + + + + + + + + + + + + + + + + + + + + + + + Comparing Values - Python Preserves + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + +

Comparing Values

+ + +
+ + + +
+ +

Preserves specifies a total ordering and +an equivalence between terms. The +preserves.compare module implements the ordering and equivalence relations.

+
>>> cmp("bzz", "c")
+-1
+>>> cmp(True, [])
+-1
+>>> lt("bzz", "c")
+True
+>>> eq("bzz", "c")
+False
+
+

Note that the ordering relates more values than Python's built-in ordering:

+
>>> [1, 2, 2] < [1, 2, "3"]
+Traceback (most recent call last):
+  ..
+TypeError: '<' not supported between instances of 'int' and 'str'
+
+>>> lt([1, 2, 2], [1, 2, "3"])
+True
+
+ + + +
+ + + + + + + + + +
+ + + +

+cmp(a, b) + +

+ + +
+ +

Returns -1 if a < b, or 0 if a = b, or 1 if a > b according to the +Preserves total order.

+ +
+ Source code in preserves/compare.py +
83
+84
+85
+86
def cmp(a, b):
+    """Returns `-1` if `a` < `b`, or `0` if `a` = `b`, or `1` if `a` > `b` according to the
+    [Preserves total order](https://preserves.dev/preserves.html#total-order)."""
+    return _cmp(preserve(a), preserve(b))
+
+
+
+ +
+ +
+ + + +

+eq(a, b) + +

+ + +
+ +

Returns True iff a = b according to the Preserves equivalence +relation.

+ +
+ Source code in preserves/compare.py +
 98
+ 99
+100
+101
def eq(a, b):
+    """Returns `True` iff `a` = `b` according to the [Preserves equivalence
+    relation](https://preserves.dev/preserves.html#equivalence)."""
+    return _eq(preserve(a), preserve(b))
+
+
+
+ +
+ +
+ + + +

+le(a, b) + +

+ + +
+ +

Returns True iff ab according to the Preserves total +order.

+ +
+ Source code in preserves/compare.py +
93
+94
+95
+96
def le(a, b):
+    """Returns `True` iff `a` ≤ `b` according to the [Preserves total
+    order](https://preserves.dev/preserves.html#total-order)."""
+    return cmp(a, b) <= 0
+
+
+
+ +
+ +
+ + + +

+lt(a, b) + +

+ + +
+ +

Returns True iff a < b according to the Preserves total +order.

+ +
+ Source code in preserves/compare.py +
88
+89
+90
+91
def lt(a, b):
+    """Returns `True` iff `a` < `b` according to the [Preserves total
+    order](https://preserves.dev/preserves.html#total-order)."""
+    return cmp(a, b) < 0
+
+
+
+ +
+ +
+ + + +

+sorted(iterable, *, key=lambda x: x, reverse=False) + +

+ + +
+ +

Returns a sorted list built from iterable, extracting a sort key using key, and +ordering according to the Preserves total +order. Directly analogous to the +built-in Python sorted +routine, except uses the +Preserves order instead of Python's less-than relation.

+ +
+ Source code in preserves/compare.py +
107
+108
+109
+110
+111
+112
+113
+114
+115
+116
def sorted(iterable, *, key=lambda x: x, reverse=False):
+    """Returns a sorted list built from `iterable`, extracting a sort key using `key`, and
+    ordering according to the [Preserves total
+    order](https://preserves.dev/preserves.html#total-order). Directly analogous to the
+    [built-in Python `sorted`
+    routine](https://docs.python.org/3/library/functions.html#sorted), except uses the
+    Preserves order instead of Python's less-than relation.
+
+    """
+    return _sorted(iterable, key=lambda x: _key(key(x)), reverse=reverse)
+
+
+
+ +
+ +
+ + + +

+sorted_items(d) + +

+ + +
+ +

Given a dictionary d, yields a list of (key, value) tuples sorted by key.

+ +
+ Source code in preserves/compare.py +
118
+119
+120
def sorted_items(d):
+    """Given a dictionary `d`, yields a list of `(key, value)` tuples sorted by `key`."""
+    return sorted(d.items(), key=_item_key)
+
+
+
+ +
+ + + +
+ +
+ +
+ +
+
+ + + Last update: + March 16, 2023 + +
+ Created: + March 16, 2023 + + +
+
+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/python/0.992.0/error/index.html b/python/0.992.0/error/index.html new file mode 100644 index 0000000..da4525e --- /dev/null +++ b/python/0.992.0/error/index.html @@ -0,0 +1,678 @@ + + + + + + + + + + + + + + + + + + + + + + + + Codec errors - Python Preserves + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + +

Codec errors

+ + +
+ + + +
+ +

The preserves.error module exports various Error subclasses.

+ + + +
+ + + + + + + + +
+ + + +

+ DecodeError + + +

+ + +
+

+ Bases: ValueError

+ + +

Raised whenever preserves.binary.Decoder or preserves.text.Parser detect invalid +input.

+ + + +
+ +
+ +
+ + + +

+ EncodeError + + +

+ + +
+

+ Bases: ValueError

+ + +

Raised whenever preserves.binary.Encoder or preserves.text.Formatter are unable to proceed.

+ + + +
+ +
+ +
+ + + +

+ ShortPacket + + +

+ + +
+

+ Bases: DecodeError

+ + +

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.

+ + + +
+ +
+ + + + +
+ +
+ +
+ +
+
+ + + Last update: + March 16, 2023 + +
+ Created: + March 16, 2023 + + +
+
+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/python/0.992.0/fold/index.html b/python/0.992.0/fold/index.html new file mode 100644 index 0000000..55d673d --- /dev/null +++ b/python/0.992.0/fold/index.html @@ -0,0 +1,651 @@ + + + + + + + + + + + + + + + + + + + + + + + + Traversing values - Python Preserves + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + +

Traversing values

+ + +
+ + + +
+ +

The preserves.fold module exports various utilities for traversing compound Values.

+ + + +
+ + + + + + + + + +
+ + + +

+map_embeddeds(f, v) + +

+ + +
+ +

Returns an equivalent copy of v, except where each contained +Embedded value is replaced by f applied to the Embedded's +embeddedValue attribute.

+
>>> map_embeddeds(lambda w: Embedded(f'w={w}'), ['a', Embedded(123), {'z': 6.0}])
+('a', #!'w=123', {'z': 6.0})
+
+ +
+ Source code in preserves/fold.py +
 5
+ 6
+ 7
+ 8
+ 9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
+27
+28
+29
def map_embeddeds(f, v):
+    """Returns an [equivalent][preserves.compare.eq] copy of `v`, except where each contained
+    [Embedded][preserves.values.Embedded] value is replaced by `f` applied to the Embedded's
+    `embeddedValue` attribute.
+
+    ```python
+    >>> map_embeddeds(lambda w: Embedded(f'w={w}'), ['a', Embedded(123), {'z': 6.0}])
+    ('a', #!'w=123', {'z': 6.0})
+
+    ```
+    """
+    def walk(v):
+        if isinstance(v, Embedded):
+            return f(v.embeddedValue)
+        elif isinstance(v, (list, tuple)):
+            return tuple(walk(w) for w in v)
+        elif isinstance(v, (set, frozenset)):
+            return frozenset(walk(w) for w in v)
+        elif isinstance(v, dict):
+            return ImmutableDict.from_kvs(walk(w) for w in dict_kvs(v))
+        elif isinstance(v, Record):
+            return Record(walk(v.key), walk(v.fields))
+        else:
+            return v
+    return walk(v)
+
+
+
+ +
+ + + +
+ +
+ +
+ +
+
+ + + Last update: + March 16, 2023 + +
+ Created: + March 16, 2023 + + +
+
+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/python/0.992.0/index.html b/python/0.992.0/index.html new file mode 100644 index 0000000..dc1dc30 --- /dev/null +++ b/python/0.992.0/index.html @@ -0,0 +1,592 @@ + + + + + + + + + + + + + + + + + + + + + + Python Preserves + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + +

Overview

+
pip install preserves
+
+

This package (preserves 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.

+ +

What is Preserves?

+

Preserves is a data model, with associated serialization formats.

+

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.

+

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.

+

Mapping between Preserves values and Python values

+

Preserves Values are categorized in the following way:

+
                      Value = Atom
+                            | Compound
+                            | Embedded
+
+                       Atom = Boolean
+                            | Float
+                            | Double
+                            | SignedInteger
+                            | String
+                            | ByteString
+                            | Symbol
+
+                   Compound = Record
+                            | Sequence
+                            | Set
+                            | Dictionary
+
+

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.

+

Python's lists and tuples correspond to Preserves Sequences, and dicts and sets to +Dictionary and Set values, respectively. Preserves Records are represented by +Record objects. Finally, embedded values are represented by +Embedded objects.

+ +
+
+ + + Last update: + March 17, 2023 + +
+ Created: + March 16, 2023 + + +
+
+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/python/0.992.0/merge/index.html b/python/0.992.0/merge/index.html new file mode 100644 index 0000000..8197ab6 --- /dev/null +++ b/python/0.992.0/merge/index.html @@ -0,0 +1,795 @@ + + + + + + + + + + + + + + + + + + + + + + + + Merging values - Python Preserves + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + +

Merging values

+ + +
+ + + +
+ +

The preserves.merge module exports various utilities for merging Values.

+ + + +
+ + + + + + + + + +
+ + + +

+merge(v0, *vs, merge_embedded=None) + +

+ + +
+ +

Repeatedly merges v0 with each element in vs using merge2, +returning the final result. The merge_embedded parameter is passed on to merge2.

+ +
+ Source code in preserves/merge.py +
 8
+ 9
+10
+11
+12
+13
+14
def merge(v0, *vs, merge_embedded=None):
+    """Repeatedly merges `v0` with each element in `vs` using [merge2][preserves.merge.merge2],
+    returning the final result. The `merge_embedded` parameter is passed on to merge2."""
+    v = v0
+    for vN in vs:
+        v = merge2(v, vN, merge_embedded=merge_embedded)
+    return v
+
+
+
+ +
+ +
+ + + +

+merge2(a, b, merge_embedded=None) + +

+ + +
+ +

Merges a and b, returning the result. Raises ValueError if, during the merge, a +pair of incompatible values is discovered.

+

If a and b are Embedded objects, their embeddedValues +are merged using merge_embedded, and the result is again wrapped in an +Embedded object.

+
>>> merge2(123, 234)
+Traceback (most recent call last):
+  ...
+ValueError: Cannot merge items
+>>> merge2(123, 123)
+123
+>>> merge2('hi', 0)
+Traceback (most recent call last):
+  ...
+ValueError: Cannot merge items
+>>> merge2([1, 2], [1, 2])
+[1, 2]
+>>> merge2([1, 2], [1, 3])
+Traceback (most recent call last):
+  ...
+ValueError: Cannot merge items
+>>> merge2({'a': 1, 'b': 2}, {'a': 1, 'c': 3})
+{'a': 1, 'b': 2, 'c': 3}
+>>> merge2({'a': 1, 'b': 2}, {'a': 10, 'c': 3})
+Traceback (most recent call last):
+  ...
+ValueError: Cannot merge items
+>>> merge2(Record('a', [1, {'x': 2}]), Record('a', [1, {'y': 3}]))
+a(1, {'x': 2, 'y': 3})
+
+ +
+ Source code in preserves/merge.py +
23
+24
+25
+26
+27
+28
+29
+30
+31
+32
+33
+34
+35
+36
+37
+38
+39
+40
+41
+42
+43
+44
+45
+46
+47
+48
+49
+50
+51
+52
+53
+54
+55
+56
+57
+58
+59
+60
+61
+62
+63
+64
+65
+66
+67
+68
+69
+70
+71
+72
+73
+74
+75
+76
+77
+78
+79
+80
+81
+82
def merge2(a, b, merge_embedded=None):
+    """Merges `a` and `b`, returning the result. Raises `ValueError` if, during the merge, a
+    pair of incompatible values is discovered.
+
+    If `a` and `b` are [Embedded][preserves.values.Embedded] objects, their `embeddedValue`s
+    are merged using `merge_embedded`, and the result is again wrapped in an
+    [Embedded][preserves.values.Embedded] object.
+
+    ```python
+    >>> merge2(123, 234)
+    Traceback (most recent call last):
+      ...
+    ValueError: Cannot merge items
+    >>> merge2(123, 123)
+    123
+    >>> merge2('hi', 0)
+    Traceback (most recent call last):
+      ...
+    ValueError: Cannot merge items
+    >>> merge2([1, 2], [1, 2])
+    [1, 2]
+    >>> merge2([1, 2], [1, 3])
+    Traceback (most recent call last):
+      ...
+    ValueError: Cannot merge items
+    >>> merge2({'a': 1, 'b': 2}, {'a': 1, 'c': 3})
+    {'a': 1, 'b': 2, 'c': 3}
+    >>> merge2({'a': 1, 'b': 2}, {'a': 10, 'c': 3})
+    Traceback (most recent call last):
+      ...
+    ValueError: Cannot merge items
+    >>> merge2(Record('a', [1, {'x': 2}]), Record('a', [1, {'y': 3}]))
+    a(1, {'x': 2, 'y': 3})
+
+    ```
+
+    """
+    if a == b:
+        return a
+    if isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)):
+        return merge_seq(a, b)
+    if isinstance(a, (set, frozenset)) and isinstance(b, (set, frozenset)):
+        _die()
+    if isinstance(a, dict) and isinstance(b, dict):
+        r = {}
+        for (ak, av) in a.items():
+            bv = b.get(ak, None)
+            r[ak] = av if bv is None else merge2(av, bv, merge_embedded=merge_embedded)
+        for (bk, bv) in b.items():
+            if bk not in r:
+                r[bk] = bv
+        return r
+    if isinstance(a, Record) and isinstance(b, Record):
+        return Record(merge2(a.key, b.key, merge_embedded=merge_embedded),
+                      merge_seq(a.fields, b.fields, merge_embedded=merge_embedded))
+    if isinstance(a, Embedded) and isinstance(b, Embedded):
+        m = (merge_embedded or merge_embedded_id)(a.embeddedValue, b.embeddedValue)
+        if m is None: _die()
+        return Embedded(m)
+    _die()
+
+
+
+ +
+ + + +
+ +
+ +
+ +
+
+ + + Last update: + March 16, 2023 + +
+ Created: + March 16, 2023 + + +
+
+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/python/0.992.0/objects.inv b/python/0.992.0/objects.inv new file mode 100644 index 0000000000000000000000000000000000000000..774441a63dad8bd2a21b3078559ed4fe285bc6b0 GIT binary patch literal 912 zcmV;B18@8zAX9K?X>NERX>N99Zgg*Qc_4OWa&u{KZXhxWBOp+6Z)#;@bUGkVd30!R zZXi%{Wpib6c4c!4BOq2~a&u{KZaN?^E-)@I3L_v?Xk{RBWo=<;Ze(S0Aa78b#rNMXCQiPX<{x4c-p0xO^@3k5Qgvl6_MI&UA4#F z+>N7+wE0k+_KFCMH#7!Zz}t0yeX$*P?Fh%{U)zAL)V5iNPqh$uGLEy*RO6Ot1XSXG0$T9aECErCc1ss>1owf59U@M=KN z8p}#S43ol_6c(Ms8C9WBHW6XbUG)(zioobPl1O0_WAq%hwg-hru#kcgoU=a=!qFzB z;RO24%o$-Jq`@^66eS4nNr~hIRxsGbSKEj*BD}a6dIEr7Vfq{b^(IWOr7}S0Fo+r8 z+K&XKq#ES4u{dSd%1b(=tDrkXyOTqR^lW3;V{&PC{#_!IIUV?38(gA@;{pLc0i{51 zGvk6dsORB!Yb;LLo47aVl>Cd2zQE=@aH2N2MA2RWwRLZxcNmO{Q^Wz^SL@_yiMH`3NoUY$yh_lFArevAlE6VB z_n7EMd|1cZqxXDU%t05JfcI=^^V7D(6}F2?1JT{-r!B)-P_)@Czdt2tA0HomBOLJc zTFe3uyWMe{&O+0N$7B=FLa(bii$$pWj!;O=4F+*uko@ubsv16o^Gbb}Xc|oWzv(j} zti~DC$rZK|yf|~cd;e?AwZSEdR#I_0^sv`XtKGM54{qen?Ljh)n4p$r;@Owp*N2&3 zXsy(}uv3uZsWXL)ypTpQ*RgzGJoNw=rL|Eu#Vo5lfES#XH_zqP&~zt`w>wA zkl(oEN!Ae+A!u^Fk9vE#vgK{U)KR7+N2khw4soqzjSMH(oRz%&UhyMa}*6HWctG1y4 literal 0 HcmV?d00001 diff --git a/python/0.992.0/path/index.html b/python/0.992.0/path/index.html new file mode 100644 index 0000000..2f978d2 --- /dev/null +++ b/python/0.992.0/path/index.html @@ -0,0 +1,979 @@ + + + + + + + + + + + + + + + + + + + + + + + + Preserves Path - Python Preserves + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + + + + + +
+
+ + + + + + + +

Preserves Path

+ + +
+ + + +
+ +

The preserves.path module implements Preserves +Path.

+

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 Value.

+

Use parse to compile a path expression, and then use the +exec method on the result to apply it to a given input:

+
parse(PATH_EXPRESSION_STRING).exec(PRESERVES_VALUE)
+    -> SEQUENCE_OF_PRESERVES_VALUES
+
+

Command-line usage

+

When preserves.path is run as a __main__ module, sys.argv[1] 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.

+

Examples

+

Setup: Loading test data

+

The following examples use testdata:

+
>>> with open('tests/samples.bin', 'rb') as f:
+...     testdata = decode_with_annotations(f.read())
+
+

Recall that samples.bin contains a binary-syntax form of the human-readable +[samples.pr](https://preserves.dev/tests/samples.pr) test data file, intended to exercise most +of the features of Preserves. In particular, the rootValue` in the file has a number of +annotations (for documentation and other purposes).

+

Example 1: Selecting string-valued documentation annotations

+

The path expression .annotations ^ Documentation . 0 / string proceeds in five steps:

+
    +
  1. .annotations selects each annotation on the root document
  2. +
  3. ^ Documentation retains only those values (each an annotation of the root) that are Records with label equal to the symbol Documentation
  4. +
  5. . 0 moves into the first child (the first field) of each such Record, which in our case is a list of other Values
  6. +
  7. / selects all immediate children of these lists
  8. +
  9. string retains only those values that are strings
  10. +
+

The result of evaluating it on testdata is as follows:

+
>>> selector = parse('.annotations ^ Documentation . 0 / string')
+>>> for result in selector.exec(testdata):
+...     print(stringify(result))
+"Individual test cases may be any of the following record types:"
+"In each test, let stripped = strip(annotatedValue),"
+"                  encodeBinary(·) produce canonical ordering and no annotations,"
+"                  looseEncodeBinary(·) produce any ordering, but with annotations,"
+"                  annotatedBinary(·) produce canonical ordering, but with annotations,"
+"                  decodeBinary(·) include annotations,"
+"                  encodeText(·) include annotations,"
+"                  decodeText(·) include annotations,"
+"and check the following numbered expectations according to the table above:"
+"Implementations may vary in their treatment of the difference between expectations"
+"21/22 and 31/32, depending on how they wish to treat end-of-stream conditions."
+
+

Example 2: Selecting tests with Records as their annotatedValues

+

The path expression // [.^ [= Test + = NondeterministicTest]] [. 1 rec] proceeds in three steps:

+
    +
  1. +

    // recursively decomposes the input, yielding all direct and indirect descendants of each input value

    +
  2. +
  3. +

    [.^ [= Test + = NondeterministicTest]] retains only those inputs (each a descendant of the root) that yield more than zero results when executed against the expression within the brackets:

    +
      +
    1. .^ selects only labels of values that are Records, filtering by type and transforming in a single step
    2. +
    3. [= Test + = NondeterministicTest] again filters by a path expression:
        +
      1. the infix + operator takes the union of matches of its arguments
      2. +
      3. the left-hand argument, = Test selects values (remember, record labels) equal to the symbol Test
      4. +
      5. the right-hand argument = NondeterministicTest selects values equal to NondeterministicTest
      6. +
      +
    4. +
    +

    The result is thus all Records anywhere inside testdata that have either Test or NondeterministicTest as their labels.

    +
  4. +
  5. +

    [. 1 rec] filters these Records by another path expression:

    +
      +
    1. . 1 selects their second field (fields are numbered from 0)
    2. +
    3. rec retains only values that are Records
    4. +
    +
  6. +
+

Evaluating the expression against testdata yields the following:

+
>>> selector = parse('// [.^ [= Test + = NondeterministicTest]] [. 1 rec]')
+>>> for result in selector.exec(testdata):
+...     print(stringify(result))
+<Test #[tLMHY2FwdHVyZbSzB2Rpc2NhcmSEhA==] <capture <discard>>>
+<Test #[tLMHb2JzZXJ2ZbSzBXNwZWFrtLMHZGlzY2FyZIS0swdjYXB0dXJltLMHZGlzY2FyZISEhIQ=] <observe <speak <discard> <capture <discard>>>>>
+<Test #[tLWzBnRpdGxlZLMGcGVyc29usAECswV0aGluZ7ABAYSwAWWxCUJsYWNrd2VsbLSzBGRhdGWwAgcdsAECsAEDhLECRHKE] <[titled person 2 thing 1] 101 "Blackwell" <date 1821 2 3> "Dr">>
+<Test #[tLMHZGlzY2FyZIQ=] <discard>>
+<Test #[tLABB7WEhA==] <7 []>>
+<Test #[tLMHZGlzY2FyZLMIc3VycHJpc2WE] <discard surprise>>
+<Test #[tLEHYVN0cmluZ7ABA7ABBIQ=] <"aString" 3 4>>
+<Test #[tLSzB2Rpc2NhcmSEsAEDsAEEhA==] <<discard> 3 4>>
+<Test #[hbMCYXK0swFShbMCYWazAWaE] @ar <R @af f>>
+<Test #[tIWzAmFyswFShbMCYWazAWaE] <@ar R @af f>>
+
+ + + +
+ + + + + + + +
+ + + +

+Predicate = syntax.Predicate + + + module-attribute + + +

+ + +
+ +

Schema definition for representing a Preserves Path Predicate.

+
+ +
+ +
+ + + +

+Selector = syntax.Selector + + + module-attribute + + +

+ + +
+ +

Schema definition for representing a sequence of Preserves Path Steps.

+
+ +
+ +
+ + + +

+syntax = load_schema_file(pathlib.Path(__file__).parent / 'path.prb').path + + + module-attribute + + +

+ + +
+ +

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.

+
+ +
+ + + +
+ + + +

+exec(self, v) + +

+ + +
+ +

WARNING: This is not a function: it is a method on +Selector, Predicate, and so on.

+
>>> sel = parse('/ [.length gt 1]')
+>>> sel.exec(['', 'a', 'ab', 'abc', 'abcd', 'bcd', 'cd', 'd', ''])
+('ab', 'abc', 'abcd', 'bcd', 'cd')
+
+ +
+ Source code in preserves/path.py +
523
+524
+525
+526
+527
+528
+529
+530
+531
+532
+533
+534
+535
+536
@extend(syntax.Function)
+def exec(self, v):
+    """WARNING: This is not a *function*: it is a *method* on
+    [Selector][preserves.path.Selector], [Predicate][preserves.path.Predicate], and so on.
+
+    ```python
+    >>> sel = parse('/ [.length gt 1]')
+    >>> sel.exec(['', 'a', 'ab', 'abc', 'abcd', 'bcd', 'cd', 'd', ''])
+    ('ab', 'abc', 'abcd', 'bcd', 'cd')
+
+    ```
+
+    """
+    return (len(self.selector.exec(v)),)
+
+
+
+ +
+ +
+ + + +

+parse(s) + +

+ + +
+ +

Parse s as a Preserves Path path expression, yielding a +Selector object. Selectors (and Predicates etc.) have an +exec method defined on them.

+

Raises ValueError if s is not a valid path expression.

+ +
+ Source code in preserves/path.py +
131
+132
+133
+134
+135
+136
+137
+138
+139
def parse(s):
+    """Parse `s` as a Preserves Path path expression, yielding a
+    [Selector][preserves.path.Selector] object. Selectors (and Predicates etc.) have an
+    [exec][preserves.path.exec] method defined on them.
+
+    Raises `ValueError` if `s` is not a valid path expression.
+
+    """
+    return parse_selector(Parser(s))
+
+
+
+ +
+ + + +
+ +
+ +
+ +
+
+ + + Last update: + March 16, 2023 + +
+ Created: + March 16, 2023 + + +
+
+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/python/0.992.0/schema/index.html b/python/0.992.0/schema/index.html new file mode 100644 index 0000000..ff546da --- /dev/null +++ b/python/0.992.0/schema/index.html @@ -0,0 +1,2378 @@ + + + + + + + + + + + + + + + + + + + + + + + + Preserves Schema - Python Preserves + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + +

Preserves Schema

+

A Preserves schema connects Preserves Values to host-language data +structures. Each definition within a schema can be processed by a +compiler to produce

+
    +
  • +

    a simple host-language type definition;

    +
  • +
  • +

    a partial parsing function from Values to instances of the + produced type; and

    +
  • +
  • +

    a total serialization function from instances of the type to + Values.

    +
  • +
+

Every parsed Value 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.

+

Schema support in Python

+ + +
+ + + +
+ +

The preserves.schema module implements Preserves +Schema for Python.

+

A Schema source file (like this one) is first +compiled using preserves-schemac 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.

+

Examples

+

Setup: Loading a schema bundle

+

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 syndicate-protocols repository.)

+

To load a schema bundle, use load_schema_file (or, +alternatively, use Compiler directly):

+
>>> bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')
+>>> type(bundle)
+<class 'preserves.schema.Namespace'>
+
+

The top-level entries in the loaded bundle are schema modules. Let's examine the stream +schema module, whose source +code +indicates that it should contain definitions for Mode, Source, Sink, etc.:

+
>>> bundle.stream                                           # doctest: +ELLIPSIS
+{'Mode': <class 'stream.Mode'>, 'Sink': <class 'stream.Sink'>, ...}
+
+

Example 1: stream.StreamListenerError, a product type

+

Drilling down further, let's consider the definition of +StreamListenerError, which appears in the source as

+
StreamListenerError = <stream-listener-error @spec any @message string> .
+
+

This reads, in the Preserves Schema +language, as the +definition of a simple product type (record, class, object) with two named fields spec and +message. Parsing a value into a StreamListenerError will only succeed if it's a record, if +the label matches, the second field (message) is a string, and it has exactly two fields.

+
>>> bundle.stream.StreamListenerError
+<class 'stream.StreamListenerError'>
+
+

The StreamListenerError class includes a decode +method that analyzes an input value:

+
>>> bundle.stream.StreamListenerError.decode(
+...     parse('<stream-listener-error <xyz> "an error">'))
+StreamListenerError {'spec': #xyz(), 'message': 'an error'}
+
+

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

+
>>> bundle.stream.StreamListenerError.decode(
+...     parse('<i-am-invalid>'))
+Traceback (most recent call last):
+  ...
+preserves.schema.SchemaDecodeFailed: Could not decode i-am-invalid using <class 'stream.StreamListenerError'>
+Most likely reason: in stream.StreamListenerError: <lit stream-listener-error> didn't match i-am-invalid
+Full explanation: 
+  in stream.StreamListenerError: <lit stream-listener-error> didn't match i-am-invalid
+
+

Alternatively, the try_decode method catches +SchemaDecodeFailed, transforming it into None:

+
>>> bundle.stream.StreamListenerError.try_decode(
+...     parse('<stream-listener-error <xyz> "an error">'))
+StreamListenerError {'spec': #xyz(), 'message': 'an error'}
+>>> bundle.stream.StreamListenerError.try_decode(
+...     parse('<i-am-invalid>'))
+
+

The class can also be instantiated directly:

+
>>> err = bundle.stream.StreamListenerError(Record(Symbol('xyz'), []), 'an error')
+>>> err
+StreamListenerError {'spec': #xyz(), 'message': 'an error'}
+
+

The fields and contents of instances can be queried:

+
>>> err.spec
+#xyz()
+>>> err.message
+'an error'
+
+

And finally, instances can of course be serialized and encoded:

+
>>> print(stringify(err))
+<stream-listener-error <xyz> "an error">
+>>> canonicalize(err)
+b'\xb4\xb3\x15stream-listener-error\xb4\xb3\x03xyz\x84\xb1\x08an error\x84'
+
+

Example 2: stream.Mode, a sum type

+

Now let's consider the definition of +Mode, +which appears in the source as

+
Mode = =bytes / @lines LineMode / <packet @size int> / <object @description any> .
+
+

This reads, in the Preserves Schema +language, as an +alternation (disjoint union, variant, sum type) of four possible kinds of value: the symbol +bytes; a LineMode value; a record with packet as its label and an integer as its only +field; or a record with object as its label and any kind of value as its only field. In +Python, this becomes:

+
>>> bundle.stream.Mode.bytes
+<class 'stream.Mode.bytes'>
+>>> bundle.stream.Mode.lines
+<class 'stream.Mode.lines'>
+>>> bundle.stream.Mode.packet
+<class 'stream.Mode.packet'>
+>>> bundle.stream.Mode.object
+<class 'stream.Mode.object'>
+
+

As before, Mode includes a decode method that analyzes +an input value:

+
>>> bundle.stream.Mode.decode(parse('bytes'))
+Mode.bytes()
+>>> bundle.stream.Mode.decode(parse('lf'))
+Mode.lines(LineMode.lf())
+>>> bundle.stream.Mode.decode(parse('<packet 123>'))
+Mode.packet {'size': 123}
+>>> bundle.stream.Mode.decode(parse('<object "?">'))
+Mode.object {'description': '?'}
+
+

Invalid input causes SchemaDecodeFailed to be raised:

+
>>> bundle.stream.Mode.decode(parse('<i-am-not-a-valid-mode>'))
+Traceback (most recent call last):
+  ...
+preserves.schema.SchemaDecodeFailed: Could not decode <i-am-not-a-valid-mode> using <class 'stream.Mode'>
+Most likely reason: in stream.LineMode.crlf: <lit crlf> didn't match <i-am-not-a-valid-mode>
+Full explanation: 
+  in stream.Mode: matching <i-am-not-a-valid-mode>
+    in stream.Mode.bytes: <lit bytes> didn't match <i-am-not-a-valid-mode>
+    in stream.Mode.lines: <ref [] LineMode> didn't match <i-am-not-a-valid-mode>
+      in stream.LineMode: matching <i-am-not-a-valid-mode>
+        in stream.LineMode.lf: <lit lf> didn't match <i-am-not-a-valid-mode>
+        in stream.LineMode.crlf: <lit crlf> didn't match <i-am-not-a-valid-mode>
+    in stream.Mode.packet: <lit packet> didn't match i-am-not-a-valid-mode
+    in stream.Mode.object: <lit object> didn't match i-am-not-a-valid-mode
+
+

The "full explanation" includes details on which parses were attempted, and why they failed.

+

Again, the try_decode method catches +SchemaDecodeFailed, transforming it into None:

+
>>> bundle.stream.Mode.try_decode(parse('bytes'))
+Mode.bytes()
+>>> bundle.stream.Mode.try_decode(parse('<i-am-not-a-valid-mode>'))
+
+

Direct instantiation is done with the variant classes, not with Mode itself:

+
>>> bundle.stream.Mode.bytes()
+Mode.bytes()
+>>> bundle.stream.Mode.lines(bundle.stream.LineMode.lf())
+Mode.lines(LineMode.lf())
+>>> bundle.stream.Mode.packet(123)
+Mode.packet {'size': 123}
+>>> bundle.stream.Mode.object('?')
+Mode.object {'description': '?'}
+
+

Fields and contents can be queried as usual:

+
>>> bundle.stream.Mode.lines(bundle.stream.LineMode.lf()).value
+LineMode.lf()
+>>> bundle.stream.Mode.packet(123).size
+123
+>>> bundle.stream.Mode.object('?').description
+'?'
+
+

And serialization and encoding are also as expected:

+
>>> print(stringify(bundle.stream.Mode.bytes()))
+bytes
+>>> print(stringify(bundle.stream.Mode.lines(bundle.stream.LineMode.lf())))
+lf
+>>> print(stringify(bundle.stream.Mode.packet(123)))
+<packet 123>
+>>> print(stringify(bundle.stream.Mode.object('?')))
+<object "?">
+>>> canonicalize(bundle.stream.Mode.object('?'))
+b'\xb4\xb3\x06object\xb1\x01?\x84'
+
+

Finally, the VARIANT attribute of instances +allows code to dispatch on what kind of data it is handling at a given moment:

+
>>> bundle.stream.Mode.bytes().VARIANT
+#bytes
+>>> bundle.stream.Mode.lines(bundle.stream.LineMode.lf()).VARIANT
+#lines
+>>> bundle.stream.Mode.packet(123).VARIANT
+#packet
+>>> bundle.stream.Mode.object('?').VARIANT
+#object
+
+ + + +
+ + + + + + + +
+ + + +

+meta = load_schema_file(__metaschema_filename).schema + + + module-attribute + + +

+ + +
+ +

Schema module Namespace corresponding to Preserves Schema's +metaschema.

+
+ +
+ + +
+ + + +

+Compiler() + +

+ + +
+ + +

Instances of Compiler populate an initially-empty +Namespace by loading and compiling schema bundle files.

+
>>> c = Compiler()
+>>> c.load('docs/syndicate-protocols-schema-bundle.bin')
+>>> type(c.root)
+<class 'preserves.schema.Namespace'>
+
+ +

Attributes:

+ + + + + + + + + + + + + + + +
NameTypeDescription
root + Namespace +

the root namespace into which top-level schema modules are installed.

+ + +
+ Source code in preserves/schema.py +
912
+913
def __init__(self):
+    self.root = Namespace(())
+
+
+ + + +
+ + + + + + + + + +
+ + + +

+load(filename) + +

+ + +
+ +

Opens the file at filename, passing the resulting file object to +load_filelike.

+ +
+ Source code in preserves/schema.py +
936
+937
+938
+939
+940
+941
def load(self, filename):
+    """Opens the file at `filename`, passing the resulting file object to
+    [load_filelike][preserves.schema.Compiler.load_filelike]."""
+    filename = pathlib.Path(filename)
+    with open(filename, 'rb') as f:
+        self.load_filelike(f, filename.stem)
+
+
+
+ +
+ +
+ + + +

+load_filelike(f, module_name=None) + +

+ + +
+ +

Reads a meta.Bundle or meta.Schema from the filelike object f, compiling and +installing it in self.root. If f contains a bundle, module_name is not used, +since the schema modules in the bundle know their own names; if f contains a plain +schema module, however, module_name is used directly if it is a string, and if it is +None, a suitable module name is computed from the name attribute of f, if it is +present. If name is absent in that case, ValueError is raised.

+ +
+ Source code in preserves/schema.py +
915
+916
+917
+918
+919
+920
+921
+922
+923
+924
+925
+926
+927
+928
+929
+930
+931
+932
+933
+934
def load_filelike(self, f, module_name=None):
+    """Reads a `meta.Bundle` or `meta.Schema` from the filelike object `f`, compiling and
+    installing it in `self.root`. If `f` contains a bundle, `module_name` is not used,
+    since the schema modules in the bundle know their own names; if `f` contains a plain
+    schema module, however, `module_name` is used directly if it is a string, and if it is
+    `None`, a suitable module name is computed from the `name` attribute of `f`, if it is
+    present. If `name` is absent in that case, `ValueError` is raised.
+
+    """
+    x = Decoder(f.read()).next()
+    if x.key == SCHEMA:
+        if module_name is None:
+            if hasattr(f, 'name'):
+                module_name = pathlib.Path(f.name).stem
+            else:
+                raise ValueError('Cannot load schema module from filelike object without a module_name')
+        self.load_schema((Symbol(module_name),), x)
+    elif x.key == BUNDLE:
+        for (p, s) in x[0].items():
+            self.load_schema(p, s)
+
+
+
+ +
+ + + +
+ +
+ +
+ +
+ + + +

+Definition(*args, **kwargs) + +

+ + +
+

+ Bases: SchemaObject

+ + +

Subclasses of Definition are used to represent both +standalone non-alternation definitions as well as alternatives within an +Enumeration.

+
>>> bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')
+
+>>> bundle.stream.StreamListenerError.FIELD_NAMES
+['spec', 'message']
+>>> bundle.stream.StreamListenerError.SAFE_FIELD_NAMES
+['spec', 'message']
+>>> bundle.stream.StreamListenerError.ENUMERATION is None
+True
+
+>>> bundle.stream.Mode.object.FIELD_NAMES
+['description']
+>>> bundle.stream.Mode.object.SAFE_FIELD_NAMES
+['description']
+>>> bundle.stream.Mode.object.ENUMERATION is bundle.stream.Mode
+True
+
+>>> bundle.stream.CreditAmount.count.FIELD_NAMES
+[]
+>>> bundle.stream.CreditAmount.count.SAFE_FIELD_NAMES
+[]
+>>> bundle.stream.CreditAmount.count.ENUMERATION is bundle.stream.CreditAmount
+True
+
+>>> bundle.stream.CreditAmount.decode(parse('123'))
+CreditAmount.count(123)
+>>> bundle.stream.CreditAmount.count(123)
+CreditAmount.count(123)
+>>> bundle.stream.CreditAmount.count(123).value
+123
+
+ + +
+ Source code in preserves/schema.py +
689
+690
+691
+692
+693
+694
+695
+696
+697
+698
+699
+700
+701
+702
+703
+704
+705
+706
+707
+708
+709
+710
+711
+712
+713
+714
def __init__(self, *args, **kwargs):
+    self._fields = args
+    if self.SIMPLE:
+        if self.EMPTY:
+            if len(args) != 0:
+                raise TypeError('%s takes no arguments' % (self._constructor_name(),))
+        else:
+            if len(args) != 1:
+                raise TypeError('%s needs exactly one argument' % (self._constructor_name(),))
+            self.value = args[0]
+    else:
+        i = 0
+        for arg in args:
+            if i >= len(self.FIELD_NAMES):
+                raise TypeError('%s given too many positional arguments' % (self._constructor_name(),))
+            setattr(self, self.SAFE_FIELD_NAMES[i], arg)
+            i = i + 1
+        for (argname, arg) in kwargs.items():
+            if hasattr(self, argname):
+                raise TypeError('%s given duplicate attribute: %r' % (self._constructor_name, argname))
+            if argname not in self.SAFE_FIELD_NAMES:
+                raise TypeError('%s given unknown attribute: %r' % (self._constructor_name, argname))
+            setattr(self, argname, arg)
+            i = i + 1
+        if i != len(self.FIELD_NAMES):
+            raise TypeError('%s needs argument(s) %r' % (self._constructor_name(), self.FIELD_NAMES))
+
+
+ + + +
+ + + + + + + +
+ + + +

+ENUMERATION = None + + + class-attribute + + +

+ + +
+ +

None for standalone top-level definitions with a module; otherwise, an +Enumeration subclass representing a top-level alternation +definition.

+
+ +
+ +
+ + + +

+FIELD_NAMES = [] + + + class-attribute + + +

+ + +
+ +

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 value attribute.

+
+ +
+ +
+ + + +

+SAFE_FIELD_NAMES = [] + + + class-attribute + + +

+ + +
+ +

The list produced by mapping safeattrname over +FIELD_NAMES.

+
+ +
+ + + + + +
+ +
+ +
+ +
+ + + +

+Enumeration() + +

+ + +
+

+ Bases: SchemaObject

+ + +

Subclasses of Enumeration represent a group of variant +options within a sum type.

+
>>> bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')
+
+>>> import pprint
+>>> pprint.pprint(bundle.stream.Mode.VARIANTS)
+[(#bytes, <class 'stream.Mode.bytes'>),
+ (#lines, <class 'stream.Mode.lines'>),
+ (#packet, <class 'stream.Mode.packet'>),
+ (#object, <class 'stream.Mode.object'>)]
+
+>>> bundle.stream.Mode.VARIANTS[0][1] is bundle.stream.Mode.bytes
+True
+
+ + +
+ Source code in preserves/schema.py +
581
+582
def __init__(self):
+    raise TypeError('Cannot create instance of Enumeration')
+
+
+ + + +
+ + + + + + + +
+ + + +

+VARIANTS = None + + + class-attribute + + +

+ + +
+ +

List of (Symbol, SchemaObject class) tuples representing the possible options within +this sum type.

+
+ +
+ + + + + +
+ +
+ +
+ +
+ + + +

+Namespace(prefix) + +

+ + +
+ + +

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.

+ +

Attributes:

+ + + + + + + + + + + + + + + +
NameTypeDescription
_prefix + tuple[Symbol] +

path to this module/Namespace from the root Namespace

+ + +
+ Source code in preserves/schema.py +
876
+877
def __init__(self, prefix):
+    self._prefix = prefix
+
+
+ + + +
+ + + + + + + + + + + +
+ +
+ +
+ +
+ + + +

+SchemaDecodeFailed(cls, p, v, failures=None) + +

+ + +
+

+ Bases: ValueError

+ + +

Raised when decode cannot find a way to parse a +given input.

+ +

Attributes:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
cls + class +

the SchemaObject subclass attempting the parse

pattern + Value +

the failing pattern, a Value conforming to schema meta.Pattern

value + Value +

the unparseable value

failures + list[SchemaDecodeFailed] +

descriptions of failed paths attempted during the match this failure describes

+ + +
+ Source code in preserves/schema.py +
311
+312
+313
+314
+315
+316
def __init__(self, cls, p, v, failures=None):
+    super().__init__()
+    self.cls = cls
+    self.pattern = p
+    self.value = v
+    self.failures = [] if failures is None else failures
+
+
+ + + +
+ + + + + + + + + + + +
+ +
+ +
+ +
+ + + +

+ SchemaObject + + +

+ + +
+ + +

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.

+
>>> bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')
+
+>>> bundle.stream.Mode.mro()[1:-1]
+[<class 'preserves.schema.Enumeration'>, <class 'preserves.schema.SchemaObject'>]
+
+>>> bundle.stream.Mode.packet.mro()[1:-1]
+[<class 'stream.Mode._ALL'>, <class 'preserves.schema.Definition'>, <class 'preserves.schema.SchemaObject'>]
+
+>>> bundle.stream.StreamListenerError.mro()[1:-1]
+[<class 'preserves.schema.Definition'>, <class 'preserves.schema.SchemaObject'>]
+
+

Illustrating the class attributes on SchemaObject +subclasses:

+
>>> bundle.stream.Mode.ROOTNS is bundle
+True
+
+>>> print(stringify(bundle.stream.Mode.SCHEMA, indent=2))
+<or [
+  [
+    "bytes"
+    <lit bytes>
+  ]
+  [
+    "lines"
+    <ref [] LineMode>
+  ]
+  [
+    "packet"
+    <rec <lit packet> <tuple [<named size <atom SignedInteger>>]>>
+  ]
+  [
+    "object"
+    <rec <lit object> <tuple [<named description any>]>>
+  ]
+]>
+
+>>> bundle.stream.Mode.MODULE_PATH
+(#stream,)
+
+>>> bundle.stream.Mode.NAME
+#Mode
+
+>>> bundle.stream.Mode.VARIANT is None
+True
+>>> bundle.stream.Mode.packet.VARIANT
+#packet
+
+ + + + + +
+ + + + + + + +
+ + + +

+MODULE_PATH = None + + + class-attribute + + +

+ + +
+ +

A sequence (tuple) of Symbols naming the path from the root +to the schema module containing this definition.

+
+ +
+ +
+ + + +

+NAME = None + + + class-attribute + + +

+ + +
+ +

A Symbol naming this definition within its module.

+
+ +
+ +
+ + + +

+ROOTNS = None + + + class-attribute + + +

+ + +
+ +

A Namespace that is the top-level environment for all +bundles included in the Compiler run that produced this +SchemaObject.

+
+ +
+ +
+ + + +

+SCHEMA = None + + + class-attribute + + +

+ + +
+ +

A Value conforming to schema meta.Definition (and thus often to meta.Pattern +etc.), interpreted by the SchemaObject machinery to drive +parsing, unparsing and so forth.

+
+ +
+ +
+ + + +

+VARIANT = None + + + class-attribute + + +

+ + +
+ +

None for Definitions (such as +bundle.stream.StreamListenerError above) and for overall +Enumerations (such as bundle.stream.Mode), or a +Symbol for variant definitions contained within an enumeration +(such as bundle.stream.Mode.packet).

+
+ +
+ + + +
+ + + +

+__preserve__() + +

+ + +
+ +

Called by preserves.values.preserve: unparses the information represented by +this instance, using its schema definition, to produce a Preserves Value.

+ +
+ Source code in preserves/schema.py +
538
+539
+540
+541
def __preserve__(self):
+    """Called by [preserves.values.preserve][]: *unparses* the information represented by
+    this instance, using its schema definition, to produce a Preserves `Value`."""
+    raise NotImplementedError('Subclass responsibility')
+
+
+
+ +
+ +
+ + + +

+decode(v) + + + classmethod + + +

+ + +
+ +

Parses v using the SCHEMA, returning a +(sub)instance of SchemaObject or raising +SchemaDecodeFailed.

+ +
+ Source code in preserves/schema.py +
444
+445
+446
+447
+448
+449
@classmethod
+def decode(cls, v):
+    """Parses `v` using the [SCHEMA][preserves.schema.SchemaObject.SCHEMA], returning a
+    (sub)instance of [SchemaObject][preserves.schema.SchemaObject] or raising
+    [SchemaDecodeFailed][preserves.schema.SchemaDecodeFailed]."""
+    raise NotImplementedError('Subclass responsibility')
+
+
+
+ +
+ +
+ + + +

+try_decode(v) + + + classmethod + + +

+ + +
+ +

Parses v using the SCHEMA, returning a +(sub)instance of SchemaObject or None if parsing +failed.

+ +
+ Source code in preserves/schema.py +
451
+452
+453
+454
+455
+456
+457
+458
+459
@classmethod
+def try_decode(cls, v):
+    """Parses `v` using the [SCHEMA][preserves.schema.SchemaObject.SCHEMA], returning a
+    (sub)instance of [SchemaObject][preserves.schema.SchemaObject] or `None` if parsing
+    failed."""
+    try:
+        return cls.decode(v)
+    except SchemaDecodeFailed:
+        return None
+
+
+
+ +
+ + + +
+ +
+ +
+ + +
+ + + +

+extend(cls) + +

+ + +
+ +

A decorator for function definitions. Useful for adding behaviour to the classes +resulting from loading a schema module:

+
>>> bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')
+
+>>> @extend(bundle.stream.LineMode.lf)
+... def what_am_i(self):
+...     return 'I am a LINEFEED linemode'
+
+>>> @extend(bundle.stream.LineMode.crlf)
+... def what_am_i(self):
+...     return 'I am a CARRIAGE-RETURN-PLUS-LINEFEED linemode'
+
+>>> bundle.stream.LineMode.lf()
+LineMode.lf()
+>>> bundle.stream.LineMode.lf().what_am_i()
+'I am a LINEFEED linemode'
+
+>>> bundle.stream.LineMode.crlf()
+LineMode.crlf()
+>>> bundle.stream.LineMode.crlf().what_am_i()
+'I am a CARRIAGE-RETURN-PLUS-LINEFEED linemode'
+
+ +
+ Source code in preserves/schema.py +
 977
+ 978
+ 979
+ 980
+ 981
+ 982
+ 983
+ 984
+ 985
+ 986
+ 987
+ 988
+ 989
+ 990
+ 991
+ 992
+ 993
+ 994
+ 995
+ 996
+ 997
+ 998
+ 999
+1000
+1001
+1002
+1003
+1004
+1005
+1006
+1007
+1008
+1009
def extend(cls):
+    """A decorator for function definitions. Useful for adding *behaviour* to the classes
+    resulting from loading a schema module:
+
+    ```python
+    >>> bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')
+
+    >>> @extend(bundle.stream.LineMode.lf)
+    ... def what_am_i(self):
+    ...     return 'I am a LINEFEED linemode'
+
+    >>> @extend(bundle.stream.LineMode.crlf)
+    ... def what_am_i(self):
+    ...     return 'I am a CARRIAGE-RETURN-PLUS-LINEFEED linemode'
+
+    >>> bundle.stream.LineMode.lf()
+    LineMode.lf()
+    >>> bundle.stream.LineMode.lf().what_am_i()
+    'I am a LINEFEED linemode'
+
+    >>> bundle.stream.LineMode.crlf()
+    LineMode.crlf()
+    >>> bundle.stream.LineMode.crlf().what_am_i()
+    'I am a CARRIAGE-RETURN-PLUS-LINEFEED linemode'
+
+    ```
+
+    """
+    @wraps(cls)
+    def extender(f):
+        setattr(cls, f.__name__, f)
+        return f
+    return extender
+
+
+
+ +
+ +
+ + + +

+load_schema_file(filename) + +

+ + +
+ +

Simple entry point to the compiler: creates a Compiler, +calls load on it, and returns its root +Namespace.

+
>>> bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')
+>>> type(bundle)
+<class 'preserves.schema.Namespace'>
+
+ +
+ Source code in preserves/schema.py +
960
+961
+962
+963
+964
+965
+966
+967
+968
+969
+970
+971
+972
+973
+974
def load_schema_file(filename):
+    """Simple entry point to the compiler: creates a [Compiler][preserves.schema.Compiler],
+    calls [load][preserves.schema.Compiler.load] on it, and returns its `root`
+    [Namespace][preserves.schema.Namespace].
+
+    ```python
+    >>> bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')
+    >>> type(bundle)
+    <class 'preserves.schema.Namespace'>
+
+    ```
+    """
+    c = Compiler()
+    c.load(filename)
+    return c.root
+
+
+
+ +
+ +
+ + + +

+safeattrname(k) + +

+ + +
+ +

Escapes Python keywords by prepending _; passes all other strings through.

+ +
+ Source code in preserves/schema.py +
613
+614
+615
def safeattrname(k):
+    """Escapes Python keywords by prepending `_`; passes all other strings through."""
+    return k + '_' if keyword.iskeyword(k) else k
+
+
+
+ +
+ + + +
+ +
+ +
+ +
+
+ + + Last update: + March 17, 2023 + +
+ Created: + March 16, 2023 + + +
+
+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/python/0.992.0/search/search_index.json b/python/0.992.0/search/search_index.json new file mode 100644 index 0000000..172c9f8 --- /dev/null +++ b/python/0.992.0/search/search_index.json @@ -0,0 +1 @@ +{"config":{"lang":["en"],"separator":"[\\s\\-]+","pipeline":["stopWordFilter"]},"docs":[{"location":"","title":"Overview","text":"
pip install preserves\n

This package (preserves 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.

  • Main package API: preserves
"},{"location":"#what-is-preserves","title":"What is Preserves?","text":"

Preserves is a data model, with associated serialization formats.

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.

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.

"},{"location":"#mapping-between-preserves-values-and-python-values","title":"Mapping between Preserves values and Python values","text":"

Preserves Values are categorized in the following way:

                      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

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.

Python's lists and tuples correspond to Preserves Sequences, and dicts and sets to Dictionary and Set values, respectively. Preserves Records are represented by Record objects. Finally, embedded values are represented by Embedded objects.

"},{"location":"api/","title":"The top-level preserves package","text":"
import preserves\n

The main package re-exports a subset of the exports of its constituent modules:

  • From preserves.values:

    • Annotated
    • Embedded
    • Float
    • ImmutableDict
    • Record
    • Symbol
    • annotate
    • is_annotated
    • preserve
    • strip_annotations
  • From preserves.error:

    • DecodeError
    • EncodeError
    • ShortPacket
  • From preserves.binary:

    • Decoder
    • Encoder
    • canonicalize
    • decode
    • decode_with_annotations
    • encode
  • From preserves.text:

    • Formatter
    • Parser
    • parse
    • parse_with_annotations
    • stringify
  • From preserves.compare:

    • cmp
  • From preserves.merge:

    • merge

It also exports the compare and fold modules themselves, permitting patterns like

>>> from preserves import *\n>>> compare.cmp(123, 234)\n-1\n

Finally, it provides a few utility aliases for common tasks:

"},{"location":"api/#preserves.dumps","title":"dumps = stringify module-attribute","text":"

This alias for stringify provides a familiar pythonesque name for converting a Preserves Value to a string.

"},{"location":"api/#preserves.loads","title":"loads = parse module-attribute","text":"

This alias for parse provides a familiar pythonesque name for converting a string to a Preserves Value.

"},{"location":"binary/","title":"Machine-oriented binary syntax","text":"

The preserves.binary module implements the Preserves machine-oriented binary syntax.

The main entry points are functions encode, canonicalize, decode, and decode_with_annotations.

>>> encode(Record(Symbol('hi'), []))\nb'\\xb4\\xb3\\x02hi\\x84'\n>>> decode(b'\\xb4\\xb3\\x02hi\\x84')\n#hi()\n
"},{"location":"binary/#preserves.binary.Decoder","title":"Decoder(packet=b'', include_annotations=False, decode_embedded=lambda x: x)","text":"

Bases: BinaryCodec

Implementation of a decoder for the machine-oriented binary Preserves syntax.

Parameters:

Name Type Description Default packet bytes

initial contents of the input buffer; may subsequently be extended by calling extend.

b'' include_annotations bool

if True, wrap each value and subvalue in an Annotated object.

False decode_embedded

function accepting a Value and returning a possibly-decoded form of that value suitable for placing into an Embedded object.

lambda x: x

Normal usage is to supply a buffer, and keep calling next until a ShortPacket exception is raised:

>>> d = Decoder(b'\\xb0\\x01{\\xb1\\x05hello\\x85\\xb3\\x01x\\xb5\\x84')\n>>> d.next()\n123\n>>> d.next()\n'hello'\n>>> d.next()\n()\n>>> d.next()\nTraceback (most recent call last):\n  ...\npreserves.error.ShortPacket: Short packet\n

Alternatively, keep calling try_next until it yields None, which is not in the domain of Preserves Values:

>>> d = Decoder(b'\\xb0\\x01{\\xb1\\x05hello\\x85\\xb3\\x01x\\xb5\\x84')\n>>> d.try_next()\n123\n>>> d.try_next()\n'hello'\n>>> d.try_next()\n()\n>>> d.try_next()\n

For convenience, Decoder implements the iterator interface, backing it with try_next, so you can simply iterate over all complete values in an input:

>>> d = Decoder(b'\\xb0\\x01{\\xb1\\x05hello\\x85\\xb3\\x01x\\xb5\\x84')\n>>> list(d)\n[123, 'hello', ()]\n
>>> for v in Decoder(b'\\xb0\\x01{\\xb1\\x05hello\\x85\\xb3\\x01x\\xb5\\x84'):\n...     print(repr(v))\n123\n'hello'\n()\n

Supply include_annotations=True to read annotations alongside the annotated values:

>>> d = Decoder(b'\\xb0\\x01{\\xb1\\x05hello\\x85\\xb3\\x01x\\xb5\\x84', include_annotations=True)\n>>> list(d)\n[123, 'hello', @#x ()]\n

If you are incrementally reading from, say, a socket, you can use extend to add new input as if comes available:

>>> d = Decoder(b'\\xb0\\x01{\\xb1\\x05he')\n>>> d.try_next()\n123\n>>> d.try_next() # returns None because the input is incomplete\n>>> d.extend(b'llo')\n>>> d.try_next()\n'hello'\n>>> d.try_next()\n

Attributes:

Name Type Description packet bytes

buffered input waiting to be processed

index int

read position within packet

Source code in preserves/binary.py
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
"},{"location":"binary/#preserves.binary.Decoder.extend","title":"extend(data)","text":"

Appends data to the remaining bytes in self.packet, trimming already-processed bytes from the front of self.packet and resetting self.index to zero.

Source code in preserves/binary.py
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
"},{"location":"binary/#preserves.binary.Decoder.next","title":"next()","text":"

Reads the next complete Value from the internal buffer, raising ShortPacket if too few bytes are available, or DecodeError if the input is invalid somehow.

Source code in preserves/binary.py
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 == 4: return self.wrap(Float.from_bytes(self.nextbytes(4)))\n        if count == 8: return self.wrap(struct.unpack('>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
"},{"location":"binary/#preserves.binary.Decoder.try_next","title":"try_next()","text":"

Like next, but returns None instead of raising ShortPacket.

Source code in preserves/binary.py
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
"},{"location":"binary/#preserves.binary.Encoder","title":"Encoder(encode_embedded=lambda x: x, canonicalize=False, include_annotations=None)","text":"

Bases: BinaryCodec

Implementation of an encoder for the machine-oriented binary Preserves syntax.

>>> e = Encoder()\n>>> e.append(123)\n>>> e.append('hello')\n>>> e.append(annotate([], Symbol('x')))\n>>> e.contents()\nb'\\xb0\\x01{\\xb1\\x05hello\\x85\\xb3\\x01x\\xb5\\x84'\n

Parameters:

Name Type Description Default encode_embedded

function accepting an Embedded.embeddedValue and returning a Value for serialization.

lambda x: x canonicalize bool

if True, ensures the serialized data are in canonical form. This is slightly more work than producing potentially-non-canonical output.

False include_annotations bool | None

if None, includes annotations in the output only when canonicalize is False, because canonical serialization of values demands omission of annotations. If explicitly True or False, however, annotations will be included resp. excluded no matter the canonicalize setting. This can be used to get canonical ordering (canonicalize=True) and annotations (include_annotations=True).

None

Attributes:

Name Type Description buffer bytearray

accumulator for the output of the encoder

Source code in preserves/binary.py
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
"},{"location":"binary/#preserves.binary.Encoder.append","title":"append(v)","text":"

Extend self.buffer with an encoding of v.

Source code in preserves/binary.py
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('>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
"},{"location":"binary/#preserves.binary.Encoder.contents","title":"contents()","text":"

Returns a bytes constructed from the contents of self.buffer.

Source code in preserves/binary.py
def contents(self):\n\"\"\"Returns a `bytes` constructed from the contents of `self.buffer`.\"\"\"\n    return bytes(self.buffer)\n
"},{"location":"binary/#preserves.binary.Encoder.reset","title":"reset()","text":"

Clears self.buffer to a fresh empty bytearray.

Source code in preserves/binary.py
def reset(self):\n\"\"\"Clears `self.buffer` to a fresh empty `bytearray`.\"\"\"\n    self.buffer = bytearray()\n
"},{"location":"binary/#preserves.binary.canonicalize","title":"canonicalize(v, **kwargs)","text":"

As encode, but sets canonicalize=True in the Encoder constructor.

Source code in preserves/binary.py
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
"},{"location":"binary/#preserves.binary.decode","title":"decode(bs, **kwargs)","text":"

Yields the first complete encoded value from bs, passing kwargs through to the Decoder constructor. Raises exceptions as per next.

Parameters:

Name Type Description Default bs bytes

encoded data to decode

required Source code in preserves/binary.py
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
"},{"location":"binary/#preserves.binary.decode_with_annotations","title":"decode_with_annotations(bs, **kwargs)","text":"

Like decode, but supplying include_annotations=True to the Decoder constructor.

Source code in preserves/binary.py
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
"},{"location":"binary/#preserves.binary.encode","title":"encode(v, **kwargs)","text":"

Encode a single Value v to a byte string. Any supplied kwargs are passed on to the underlying Encoder constructor.

Source code in preserves/binary.py
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
"},{"location":"compare/","title":"Comparing Values","text":"

Preserves specifies a total ordering and an equivalence between terms. The preserves.compare module implements the ordering and equivalence relations.

>>> cmp(\"bzz\", \"c\")\n-1\n>>> cmp(True, [])\n-1\n>>> lt(\"bzz\", \"c\")\nTrue\n>>> eq(\"bzz\", \"c\")\nFalse\n

Note that the ordering relates more values than Python's built-in ordering:

>>> [1, 2, 2] < [1, 2, \"3\"]\nTraceback (most recent call last):\n  ..\nTypeError: '<' not supported between instances of 'int' and 'str'\n\n>>> lt([1, 2, 2], [1, 2, \"3\"])\nTrue\n
"},{"location":"compare/#preserves.compare.cmp","title":"cmp(a, b)","text":"

Returns -1 if a < b, or 0 if a = b, or 1 if a > b according to the Preserves total order.

Source code in preserves/compare.py
def cmp(a, b):\n\"\"\"Returns `-1` if `a` < `b`, or `0` if `a` = `b`, or `1` if `a` > `b` according to the\n    [Preserves total order](https://preserves.dev/preserves.html#total-order).\"\"\"\n    return _cmp(preserve(a), preserve(b))\n
"},{"location":"compare/#preserves.compare.eq","title":"eq(a, b)","text":"

Returns True iff a = b according to the Preserves equivalence relation.

Source code in preserves/compare.py
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
"},{"location":"compare/#preserves.compare.le","title":"le(a, b)","text":"

Returns True iff a \u2264 b according to the Preserves total order.

Source code in preserves/compare.py
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) <= 0\n
"},{"location":"compare/#preserves.compare.lt","title":"lt(a, b)","text":"

Returns True iff a < b according to the Preserves total order.

Source code in preserves/compare.py
def lt(a, b):\n\"\"\"Returns `True` iff `a` < `b` according to the [Preserves total\n    order](https://preserves.dev/preserves.html#total-order).\"\"\"\n    return cmp(a, b) < 0\n
"},{"location":"compare/#preserves.compare.sorted","title":"sorted(iterable, *, key=lambda x: x, reverse=False)","text":"

Returns a sorted list built from iterable, extracting a sort key using key, and ordering according to the Preserves total order. Directly analogous to the built-in Python sorted routine, except uses the Preserves order instead of Python's less-than relation.

Source code in preserves/compare.py
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
"},{"location":"compare/#preserves.compare.sorted_items","title":"sorted_items(d)","text":"

Given a dictionary d, yields a list of (key, value) tuples sorted by key.

Source code in preserves/compare.py
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
"},{"location":"error/","title":"Codec errors","text":"

The preserves.error module exports various Error subclasses.

"},{"location":"error/#preserves.error.DecodeError","title":"DecodeError","text":"

Bases: ValueError

Raised whenever preserves.binary.Decoder or preserves.text.Parser detect invalid input.

"},{"location":"error/#preserves.error.EncodeError","title":"EncodeError","text":"

Bases: ValueError

Raised whenever preserves.binary.Encoder or preserves.text.Formatter are unable to proceed.

"},{"location":"error/#preserves.error.ShortPacket","title":"ShortPacket","text":"

Bases: DecodeError

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.

"},{"location":"fold/","title":"Traversing values","text":"

The preserves.fold module exports various utilities for traversing compound Values.

"},{"location":"fold/#preserves.fold.map_embeddeds","title":"map_embeddeds(f, v)","text":"

Returns an equivalent copy of v, except where each contained Embedded value is replaced by f applied to the Embedded's embeddedValue attribute.

>>> map_embeddeds(lambda w: Embedded(f'w={w}'), ['a', Embedded(123), {'z': 6.0}])\n('a', #!'w=123', {'z': 6.0})\n
Source code in preserves/fold.py
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    >>> 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
"},{"location":"merge/","title":"Merging values","text":"

The preserves.merge module exports various utilities for merging Values.

"},{"location":"merge/#preserves.merge.merge","title":"merge(v0, *vs, merge_embedded=None)","text":"

Repeatedly merges v0 with each element in vs using merge2, returning the final result. The merge_embedded parameter is passed on to merge2.

Source code in preserves/merge.py
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
"},{"location":"merge/#preserves.merge.merge2","title":"merge2(a, b, merge_embedded=None)","text":"

Merges a and b, returning the result. Raises ValueError if, during the merge, a pair of incompatible values is discovered.

If a and b are Embedded objects, their embeddedValues are merged using merge_embedded, and the result is again wrapped in an Embedded object.

>>> merge2(123, 234)\nTraceback (most recent call last):\n  ...\nValueError: Cannot merge items\n>>> merge2(123, 123)\n123\n>>> merge2('hi', 0)\nTraceback (most recent call last):\n  ...\nValueError: Cannot merge items\n>>> merge2([1, 2], [1, 2])\n[1, 2]\n>>> merge2([1, 2], [1, 3])\nTraceback (most recent call last):\n  ...\nValueError: Cannot merge items\n>>> merge2({'a': 1, 'b': 2}, {'a': 1, 'c': 3})\n{'a': 1, 'b': 2, 'c': 3}\n>>> merge2({'a': 1, 'b': 2}, {'a': 10, 'c': 3})\nTraceback (most recent call last):\n  ...\nValueError: Cannot merge items\n>>> merge2(Record('a', [1, {'x': 2}]), Record('a', [1, {'y': 3}]))\na(1, {'x': 2, 'y': 3})\n
Source code in preserves/merge.py
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    >>> merge2(123, 234)\n    Traceback (most recent call last):\n      ...\n    ValueError: Cannot merge items\n    >>> merge2(123, 123)\n    123\n    >>> merge2('hi', 0)\n    Traceback (most recent call last):\n      ...\n    ValueError: Cannot merge items\n    >>> merge2([1, 2], [1, 2])\n    [1, 2]\n    >>> merge2([1, 2], [1, 3])\n    Traceback (most recent call last):\n      ...\n    ValueError: Cannot merge items\n    >>> merge2({'a': 1, 'b': 2}, {'a': 1, 'c': 3})\n    {'a': 1, 'b': 2, 'c': 3}\n    >>> merge2({'a': 1, 'b': 2}, {'a': 10, 'c': 3})\n    Traceback (most recent call last):\n      ...\n    ValueError: Cannot merge items\n    >>> 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
"},{"location":"path/","title":"Preserves Path","text":"

The preserves.path module implements Preserves Path.

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 Value.

Use parse to compile a path expression, and then use the exec method on the result to apply it to a given input:

parse(PATH_EXPRESSION_STRING).exec(PRESERVES_VALUE)\n    -> SEQUENCE_OF_PRESERVES_VALUES\n
"},{"location":"path/#preserves.path--command-line-usage","title":"Command-line usage","text":"

When preserves.path is run as a __main__ module, sys.argv[1] 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.

"},{"location":"path/#preserves.path--examples","title":"Examples","text":""},{"location":"path/#preserves.path--setup-loading-test-data","title":"Setup: Loading test data","text":"

The following examples use testdata:

>>> with open('tests/samples.bin', 'rb') as f:\n...     testdata = decode_with_annotations(f.read())\n

Recall that samples.bin contains a binary-syntax form of the human-readable [samples.pr](https://preserves.dev/tests/samples.pr) test data file, intended to exercise most of the features of Preserves. In particular, the rootValue` in the file has a number of annotations (for documentation and other purposes).

"},{"location":"path/#preserves.path--example-1-selecting-string-valued-documentation-annotations","title":"Example 1: Selecting string-valued documentation annotations","text":"

The path expression .annotations ^ Documentation . 0 / string proceeds in five steps:

  1. .annotations selects each annotation on the root document
  2. ^ Documentation retains only those values (each an annotation of the root) that are Records with label equal to the symbol Documentation
  3. . 0 moves into the first child (the first field) of each such Record, which in our case is a list of other Values
  4. / selects all immediate children of these lists
  5. string retains only those values that are strings

The result of evaluating it on testdata is as follows:

>>> selector = parse('.annotations ^ Documentation . 0 / string')\n>>> 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
"},{"location":"path/#preserves.path--example-2-selecting-tests-with-records-as-their-annotatedvalues","title":"Example 2: Selecting tests with Records as their annotatedValues","text":"

The path expression // [.^ [= Test + = NondeterministicTest]] [. 1 rec] proceeds in three steps:

  1. // recursively decomposes the input, yielding all direct and indirect descendants of each input value

  2. [.^ [= Test + = NondeterministicTest]] retains only those inputs (each a descendant of the root) that yield more than zero results when executed against the expression within the brackets:

    1. .^ selects only labels of values that are Records, filtering by type and transforming in a single step
    2. [= Test + = NondeterministicTest] again filters by a path expression:
      1. the infix + operator takes the union of matches of its arguments
      2. the left-hand argument, = Test selects values (remember, record labels) equal to the symbol Test
      3. the right-hand argument = NondeterministicTest selects values equal to NondeterministicTest

    The result is thus all Records anywhere inside testdata that have either Test or NondeterministicTest as their labels.

  3. [. 1 rec] filters these Records by another path expression:

    1. . 1 selects their second field (fields are numbered from 0)
    2. rec retains only values that are Records

Evaluating the expression against testdata yields the following:

>>> selector = parse('// [.^ [= Test + = NondeterministicTest]] [. 1 rec]')\n>>> for result in selector.exec(testdata):\n...     print(stringify(result))\n<Test #[tLMHY2FwdHVyZbSzB2Rpc2NhcmSEhA==] <capture <discard>>>\n<Test #[tLMHb2JzZXJ2ZbSzBXNwZWFrtLMHZGlzY2FyZIS0swdjYXB0dXJltLMHZGlzY2FyZISEhIQ=] <observe <speak <discard> <capture <discard>>>>>\n<Test #[tLWzBnRpdGxlZLMGcGVyc29usAECswV0aGluZ7ABAYSwAWWxCUJsYWNrd2VsbLSzBGRhdGWwAgcdsAECsAEDhLECRHKE] <[titled person 2 thing 1] 101 \"Blackwell\" <date 1821 2 3> \"Dr\">>\n<Test #[tLMHZGlzY2FyZIQ=] <discard>>\n<Test #[tLABB7WEhA==] <7 []>>\n<Test #[tLMHZGlzY2FyZLMIc3VycHJpc2WE] <discard surprise>>\n<Test #[tLEHYVN0cmluZ7ABA7ABBIQ=] <\"aString\" 3 4>>\n<Test #[tLSzB2Rpc2NhcmSEsAEDsAEEhA==] <<discard> 3 4>>\n<Test #[hbMCYXK0swFShbMCYWazAWaE] @ar <R @af f>>\n<Test #[tIWzAmFyswFShbMCYWazAWaE] <@ar R @af f>>\n
"},{"location":"path/#preserves.path.Predicate","title":"Predicate = syntax.Predicate module-attribute","text":"

Schema definition for representing a Preserves Path Predicate.

"},{"location":"path/#preserves.path.Selector","title":"Selector = syntax.Selector module-attribute","text":"

Schema definition for representing a sequence of Preserves Path Steps.

"},{"location":"path/#preserves.path.syntax","title":"syntax = load_schema_file(pathlib.Path(__file__).parent / 'path.prb').path module-attribute","text":"

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.

"},{"location":"path/#preserves.path.exec","title":"exec(self, v)","text":"

WARNING: This is not a function: it is a method on Selector, Predicate, and so on.

>>> sel = parse('/ [.length gt 1]')\n>>> sel.exec(['', 'a', 'ab', 'abc', 'abcd', 'bcd', 'cd', 'd', ''])\n('ab', 'abc', 'abcd', 'bcd', 'cd')\n
Source code in preserves/path.py
@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    >>> sel = parse('/ [.length gt 1]')\n    >>> 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
"},{"location":"path/#preserves.path.parse","title":"parse(s)","text":"

Parse s as a Preserves Path path expression, yielding a Selector object. Selectors (and Predicates etc.) have an exec method defined on them.

Raises ValueError if s is not a valid path expression.

Source code in preserves/path.py
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
"},{"location":"schema/","title":"Preserves Schema","text":"

A Preserves schema connects Preserves Values to host-language data structures. Each definition within a schema can be processed by a compiler to produce

  • a simple host-language type definition;

  • a partial parsing function from Values to instances of the produced type; and

  • a total serialization function from instances of the type to Values.

Every parsed Value 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.

"},{"location":"schema/#schema-support-in-python","title":"Schema support in Python","text":"

The preserves.schema module implements Preserves Schema for Python.

A Schema source file (like this one) is first compiled using preserves-schemac 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.

"},{"location":"schema/#preserves.schema--examples","title":"Examples","text":""},{"location":"schema/#preserves.schema--setup-loading-a-schema-bundle","title":"Setup: Loading a schema bundle","text":"

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 syndicate-protocols repository.)

To load a schema bundle, use load_schema_file (or, alternatively, use Compiler directly):

>>> bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')\n>>> type(bundle)\n<class 'preserves.schema.Namespace'>\n

The top-level entries in the loaded bundle are schema modules. Let's examine the stream schema module, whose source code indicates that it should contain definitions for Mode, Source, Sink, etc.:

>>> bundle.stream                                           # doctest: +ELLIPSIS\n{'Mode': <class 'stream.Mode'>, 'Sink': <class 'stream.Sink'>, ...}\n
"},{"location":"schema/#preserves.schema--example-1-streamstreamlistenererror-a-product-type","title":"Example 1: stream.StreamListenerError, a product type","text":"

Drilling down further, let's consider the definition of StreamListenerError, which appears in the source as

StreamListenerError = <stream-listener-error @spec any @message string> .\n

This reads, in the Preserves Schema language, as the definition of a simple product type (record, class, object) with two named fields spec and message. Parsing a value into a StreamListenerError will only succeed if it's a record, if the label matches, the second field (message) is a string, and it has exactly two fields.

>>> bundle.stream.StreamListenerError\n<class 'stream.StreamListenerError'>\n

The StreamListenerError class includes a decode method that analyzes an input value:

>>> bundle.stream.StreamListenerError.decode(\n...     parse('<stream-listener-error <xyz> \"an error\">'))\nStreamListenerError {'spec': #xyz(), 'message': 'an error'}\n

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

>>> bundle.stream.StreamListenerError.decode(\n...     parse('<i-am-invalid>'))\nTraceback (most recent call last):\n  ...\npreserves.schema.SchemaDecodeFailed: Could not decode i-am-invalid using <class 'stream.StreamListenerError'>\nMost likely reason: in stream.StreamListenerError: <lit stream-listener-error> didn't match i-am-invalid\nFull explanation: \n  in stream.StreamListenerError: <lit stream-listener-error> didn't match i-am-invalid\n

Alternatively, the try_decode method catches SchemaDecodeFailed, transforming it into None:

>>> bundle.stream.StreamListenerError.try_decode(\n...     parse('<stream-listener-error <xyz> \"an error\">'))\nStreamListenerError {'spec': #xyz(), 'message': 'an error'}\n>>> bundle.stream.StreamListenerError.try_decode(\n...     parse('<i-am-invalid>'))\n

The class can also be instantiated directly:

>>> err = bundle.stream.StreamListenerError(Record(Symbol('xyz'), []), 'an error')\n>>> err\nStreamListenerError {'spec': #xyz(), 'message': 'an error'}\n

The fields and contents of instances can be queried:

>>> err.spec\n#xyz()\n>>> err.message\n'an error'\n

And finally, instances can of course be serialized and encoded:

>>> print(stringify(err))\n<stream-listener-error <xyz> \"an error\">\n>>> canonicalize(err)\nb'\\xb4\\xb3\\x15stream-listener-error\\xb4\\xb3\\x03xyz\\x84\\xb1\\x08an error\\x84'\n
"},{"location":"schema/#preserves.schema--example-2-streammode-a-sum-type","title":"Example 2: stream.Mode, a sum type","text":"

Now let's consider the definition of Mode, which appears in the source as

Mode = =bytes / @lines LineMode / <packet @size int> / <object @description any> .\n

This reads, in the Preserves Schema language, as an alternation (disjoint union, variant, sum type) of four possible kinds of value: the symbol bytes; a LineMode value; a record with packet as its label and an integer as its only field; or a record with object as its label and any kind of value as its only field. In Python, this becomes:

>>> bundle.stream.Mode.bytes\n<class 'stream.Mode.bytes'>\n>>> bundle.stream.Mode.lines\n<class 'stream.Mode.lines'>\n>>> bundle.stream.Mode.packet\n<class 'stream.Mode.packet'>\n>>> bundle.stream.Mode.object\n<class 'stream.Mode.object'>\n

As before, Mode includes a decode method that analyzes an input value:

>>> bundle.stream.Mode.decode(parse('bytes'))\nMode.bytes()\n>>> bundle.stream.Mode.decode(parse('lf'))\nMode.lines(LineMode.lf())\n>>> bundle.stream.Mode.decode(parse('<packet 123>'))\nMode.packet {'size': 123}\n>>> bundle.stream.Mode.decode(parse('<object \"?\">'))\nMode.object {'description': '?'}\n

Invalid input causes SchemaDecodeFailed to be raised:

>>> bundle.stream.Mode.decode(parse('<i-am-not-a-valid-mode>'))\nTraceback (most recent call last):\n  ...\npreserves.schema.SchemaDecodeFailed: Could not decode <i-am-not-a-valid-mode> using <class 'stream.Mode'>\nMost likely reason: in stream.LineMode.crlf: <lit crlf> didn't match <i-am-not-a-valid-mode>\nFull explanation: \n  in stream.Mode: matching <i-am-not-a-valid-mode>\n    in stream.Mode.bytes: <lit bytes> didn't match <i-am-not-a-valid-mode>\n    in stream.Mode.lines: <ref [] LineMode> didn't match <i-am-not-a-valid-mode>\n      in stream.LineMode: matching <i-am-not-a-valid-mode>\n        in stream.LineMode.lf: <lit lf> didn't match <i-am-not-a-valid-mode>\n        in stream.LineMode.crlf: <lit crlf> didn't match <i-am-not-a-valid-mode>\n    in stream.Mode.packet: <lit packet> didn't match i-am-not-a-valid-mode\n    in stream.Mode.object: <lit object> didn't match i-am-not-a-valid-mode\n

The \"full explanation\" includes details on which parses were attempted, and why they failed.

Again, the try_decode method catches SchemaDecodeFailed, transforming it into None:

>>> bundle.stream.Mode.try_decode(parse('bytes'))\nMode.bytes()\n>>> bundle.stream.Mode.try_decode(parse('<i-am-not-a-valid-mode>'))\n

Direct instantiation is done with the variant classes, not with Mode itself:

>>> bundle.stream.Mode.bytes()\nMode.bytes()\n>>> bundle.stream.Mode.lines(bundle.stream.LineMode.lf())\nMode.lines(LineMode.lf())\n>>> bundle.stream.Mode.packet(123)\nMode.packet {'size': 123}\n>>> bundle.stream.Mode.object('?')\nMode.object {'description': '?'}\n

Fields and contents can be queried as usual:

>>> bundle.stream.Mode.lines(bundle.stream.LineMode.lf()).value\nLineMode.lf()\n>>> bundle.stream.Mode.packet(123).size\n123\n>>> bundle.stream.Mode.object('?').description\n'?'\n

And serialization and encoding are also as expected:

>>> print(stringify(bundle.stream.Mode.bytes()))\nbytes\n>>> print(stringify(bundle.stream.Mode.lines(bundle.stream.LineMode.lf())))\nlf\n>>> print(stringify(bundle.stream.Mode.packet(123)))\n<packet 123>\n>>> print(stringify(bundle.stream.Mode.object('?')))\n<object \"?\">\n>>> canonicalize(bundle.stream.Mode.object('?'))\nb'\\xb4\\xb3\\x06object\\xb1\\x01?\\x84'\n

Finally, the VARIANT attribute of instances allows code to dispatch on what kind of data it is handling at a given moment:

>>> bundle.stream.Mode.bytes().VARIANT\n#bytes\n>>> bundle.stream.Mode.lines(bundle.stream.LineMode.lf()).VARIANT\n#lines\n>>> bundle.stream.Mode.packet(123).VARIANT\n#packet\n>>> bundle.stream.Mode.object('?').VARIANT\n#object\n
"},{"location":"schema/#preserves.schema.meta","title":"meta = load_schema_file(__metaschema_filename).schema module-attribute","text":"

Schema module Namespace corresponding to Preserves Schema's metaschema.

"},{"location":"schema/#preserves.schema.Compiler","title":"Compiler()","text":"

Instances of Compiler populate an initially-empty Namespace by loading and compiling schema bundle files.

>>> c = Compiler()\n>>> c.load('docs/syndicate-protocols-schema-bundle.bin')\n>>> type(c.root)\n<class 'preserves.schema.Namespace'>\n

Attributes:

Name Type Description root Namespace

the root namespace into which top-level schema modules are installed.

Source code in preserves/schema.py
def __init__(self):\n    self.root = Namespace(())\n
"},{"location":"schema/#preserves.schema.Compiler.load","title":"load(filename)","text":"

Opens the file at filename, passing the resulting file object to load_filelike.

Source code in preserves/schema.py
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
"},{"location":"schema/#preserves.schema.Compiler.load_filelike","title":"load_filelike(f, module_name=None)","text":"

Reads a meta.Bundle or meta.Schema from the filelike object f, compiling and installing it in self.root. If f contains a bundle, module_name is not used, since the schema modules in the bundle know their own names; if f contains a plain schema module, however, module_name is used directly if it is a string, and if it is None, a suitable module name is computed from the name attribute of f, if it is present. If name is absent in that case, ValueError is raised.

Source code in preserves/schema.py
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
"},{"location":"schema/#preserves.schema.Definition","title":"Definition(*args, **kwargs)","text":"

Bases: SchemaObject

Subclasses of Definition are used to represent both standalone non-alternation definitions as well as alternatives within an Enumeration.

>>> bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')\n\n>>> bundle.stream.StreamListenerError.FIELD_NAMES\n['spec', 'message']\n>>> bundle.stream.StreamListenerError.SAFE_FIELD_NAMES\n['spec', 'message']\n>>> bundle.stream.StreamListenerError.ENUMERATION is None\nTrue\n\n>>> bundle.stream.Mode.object.FIELD_NAMES\n['description']\n>>> bundle.stream.Mode.object.SAFE_FIELD_NAMES\n['description']\n>>> bundle.stream.Mode.object.ENUMERATION is bundle.stream.Mode\nTrue\n\n>>> bundle.stream.CreditAmount.count.FIELD_NAMES\n[]\n>>> bundle.stream.CreditAmount.count.SAFE_FIELD_NAMES\n[]\n>>> bundle.stream.CreditAmount.count.ENUMERATION is bundle.stream.CreditAmount\nTrue\n\n>>> bundle.stream.CreditAmount.decode(parse('123'))\nCreditAmount.count(123)\n>>> bundle.stream.CreditAmount.count(123)\nCreditAmount.count(123)\n>>> bundle.stream.CreditAmount.count(123).value\n123\n
Source code in preserves/schema.py
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 >= 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
"},{"location":"schema/#preserves.schema.Definition.ENUMERATION","title":"ENUMERATION = None class-attribute","text":"

None for standalone top-level definitions with a module; otherwise, an Enumeration subclass representing a top-level alternation definition.

"},{"location":"schema/#preserves.schema.Definition.FIELD_NAMES","title":"FIELD_NAMES = [] class-attribute","text":"

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 value attribute.

"},{"location":"schema/#preserves.schema.Definition.SAFE_FIELD_NAMES","title":"SAFE_FIELD_NAMES = [] class-attribute","text":"

The list produced by mapping safeattrname over FIELD_NAMES.

"},{"location":"schema/#preserves.schema.Enumeration","title":"Enumeration()","text":"

Bases: SchemaObject

Subclasses of Enumeration represent a group of variant options within a sum type.

>>> bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')\n\n>>> import pprint\n>>> pprint.pprint(bundle.stream.Mode.VARIANTS)\n[(#bytes, <class 'stream.Mode.bytes'>),\n (#lines, <class 'stream.Mode.lines'>),\n (#packet, <class 'stream.Mode.packet'>),\n (#object, <class 'stream.Mode.object'>)]\n\n>>> bundle.stream.Mode.VARIANTS[0][1] is bundle.stream.Mode.bytes\nTrue\n
Source code in preserves/schema.py
def __init__(self):\n    raise TypeError('Cannot create instance of Enumeration')\n
"},{"location":"schema/#preserves.schema.Enumeration.VARIANTS","title":"VARIANTS = None class-attribute","text":"

List of (Symbol, SchemaObject class) tuples representing the possible options within this sum type.

"},{"location":"schema/#preserves.schema.Namespace","title":"Namespace(prefix)","text":"

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.

Attributes:

Name Type Description _prefix tuple[Symbol]

path to this module/Namespace from the root Namespace

Source code in preserves/schema.py
def __init__(self, prefix):\n    self._prefix = prefix\n
"},{"location":"schema/#preserves.schema.SchemaDecodeFailed","title":"SchemaDecodeFailed(cls, p, v, failures=None)","text":"

Bases: ValueError

Raised when decode cannot find a way to parse a given input.

Attributes:

Name Type Description cls class

the SchemaObject subclass attempting the parse

pattern Value

the failing pattern, a Value conforming to schema meta.Pattern

value Value

the unparseable value

failures list[SchemaDecodeFailed]

descriptions of failed paths attempted during the match this failure describes

Source code in preserves/schema.py
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
"},{"location":"schema/#preserves.schema.SchemaObject","title":"SchemaObject","text":"

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.

>>> bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')\n\n>>> bundle.stream.Mode.mro()[1:-1]\n[<class 'preserves.schema.Enumeration'>, <class 'preserves.schema.SchemaObject'>]\n\n>>> bundle.stream.Mode.packet.mro()[1:-1]\n[<class 'stream.Mode._ALL'>, <class 'preserves.schema.Definition'>, <class 'preserves.schema.SchemaObject'>]\n\n>>> bundle.stream.StreamListenerError.mro()[1:-1]\n[<class 'preserves.schema.Definition'>, <class 'preserves.schema.SchemaObject'>]\n

Illustrating the class attributes on SchemaObject subclasses:

>>> bundle.stream.Mode.ROOTNS is bundle\nTrue\n\n>>> print(stringify(bundle.stream.Mode.SCHEMA, indent=2))\n<or [\n  [\n    \"bytes\"\n    <lit bytes>\n  ]\n  [\n    \"lines\"\n    <ref [] LineMode>\n  ]\n  [\n    \"packet\"\n    <rec <lit packet> <tuple [<named size <atom SignedInteger>>]>>\n  ]\n  [\n    \"object\"\n    <rec <lit object> <tuple [<named description any>]>>\n  ]\n]>\n\n>>> bundle.stream.Mode.MODULE_PATH\n(#stream,)\n\n>>> bundle.stream.Mode.NAME\n#Mode\n\n>>> bundle.stream.Mode.VARIANT is None\nTrue\n>>> bundle.stream.Mode.packet.VARIANT\n#packet\n
"},{"location":"schema/#preserves.schema.SchemaObject.MODULE_PATH","title":"MODULE_PATH = None class-attribute","text":"

A sequence (tuple) of Symbols naming the path from the root to the schema module containing this definition.

"},{"location":"schema/#preserves.schema.SchemaObject.NAME","title":"NAME = None class-attribute","text":"

A Symbol naming this definition within its module.

"},{"location":"schema/#preserves.schema.SchemaObject.ROOTNS","title":"ROOTNS = None class-attribute","text":"

A Namespace that is the top-level environment for all bundles included in the Compiler run that produced this SchemaObject.

"},{"location":"schema/#preserves.schema.SchemaObject.SCHEMA","title":"SCHEMA = None class-attribute","text":"

A Value conforming to schema meta.Definition (and thus often to meta.Pattern etc.), interpreted by the SchemaObject machinery to drive parsing, unparsing and so forth.

"},{"location":"schema/#preserves.schema.SchemaObject.VARIANT","title":"VARIANT = None class-attribute","text":"

None for Definitions (such as bundle.stream.StreamListenerError above) and for overall Enumerations (such as bundle.stream.Mode), or a Symbol for variant definitions contained within an enumeration (such as bundle.stream.Mode.packet).

"},{"location":"schema/#preserves.schema.SchemaObject.__preserve__","title":"__preserve__()","text":"

Called by preserves.values.preserve: unparses the information represented by this instance, using its schema definition, to produce a Preserves Value.

Source code in preserves/schema.py
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
"},{"location":"schema/#preserves.schema.SchemaObject.decode","title":"decode(v) classmethod","text":"

Parses v using the SCHEMA, returning a (sub)instance of SchemaObject or raising SchemaDecodeFailed.

Source code in preserves/schema.py
@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
"},{"location":"schema/#preserves.schema.SchemaObject.try_decode","title":"try_decode(v) classmethod","text":"

Parses v using the SCHEMA, returning a (sub)instance of SchemaObject or None if parsing failed.

Source code in preserves/schema.py
@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
"},{"location":"schema/#preserves.schema.extend","title":"extend(cls)","text":"

A decorator for function definitions. Useful for adding behaviour to the classes resulting from loading a schema module:

>>> bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')\n\n>>> @extend(bundle.stream.LineMode.lf)\n... def what_am_i(self):\n...     return 'I am a LINEFEED linemode'\n\n>>> @extend(bundle.stream.LineMode.crlf)\n... def what_am_i(self):\n...     return 'I am a CARRIAGE-RETURN-PLUS-LINEFEED linemode'\n\n>>> bundle.stream.LineMode.lf()\nLineMode.lf()\n>>> bundle.stream.LineMode.lf().what_am_i()\n'I am a LINEFEED linemode'\n\n>>> bundle.stream.LineMode.crlf()\nLineMode.crlf()\n>>> bundle.stream.LineMode.crlf().what_am_i()\n'I am a CARRIAGE-RETURN-PLUS-LINEFEED linemode'\n
Source code in preserves/schema.py
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    >>> bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')\n\n    >>> @extend(bundle.stream.LineMode.lf)\n    ... def what_am_i(self):\n    ...     return 'I am a LINEFEED linemode'\n\n    >>> @extend(bundle.stream.LineMode.crlf)\n    ... def what_am_i(self):\n    ...     return 'I am a CARRIAGE-RETURN-PLUS-LINEFEED linemode'\n\n    >>> bundle.stream.LineMode.lf()\n    LineMode.lf()\n    >>> bundle.stream.LineMode.lf().what_am_i()\n    'I am a LINEFEED linemode'\n\n    >>> bundle.stream.LineMode.crlf()\n    LineMode.crlf()\n    >>> 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
"},{"location":"schema/#preserves.schema.load_schema_file","title":"load_schema_file(filename)","text":"

Simple entry point to the compiler: creates a Compiler, calls load on it, and returns its root Namespace.

>>> bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')\n>>> type(bundle)\n<class 'preserves.schema.Namespace'>\n
Source code in preserves/schema.py
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    >>> bundle = load_schema_file('docs/syndicate-protocols-schema-bundle.bin')\n    >>> type(bundle)\n    <class 'preserves.schema.Namespace'>\n\n    ```\n    \"\"\"\n    c = Compiler()\n    c.load(filename)\n    return c.root\n
"},{"location":"schema/#preserves.schema.safeattrname","title":"safeattrname(k)","text":"

Escapes Python keywords by prepending _; passes all other strings through.

Source code in preserves/schema.py
def safeattrname(k):\n\"\"\"Escapes Python keywords by prepending `_`; passes all other strings through.\"\"\"\n    return k + '_' if keyword.iskeyword(k) else k\n
"},{"location":"text/","title":"Human-readable text syntax","text":"

The preserves.text module implements the Preserves human-readable text syntax.

The main entry points are functions stringify, parse, and parse_with_annotations.

>>> stringify(Record(Symbol('hi'), [1, [2, 3]]))\n'<hi 1 [2 3]>'\n>>> parse('<hi 1 [2 3]>')\n#hi(1, (2, 3))\n
"},{"location":"text/#preserves.text.Formatter","title":"Formatter(format_embedded=lambda x: x, indent=None, with_commas=False, trailing_comma=False, include_annotations=True)","text":"

Bases: TextCodec

Printer (and indenting pretty-printer) for producing human-readable syntax from Preserves Values.

>>> f = Formatter()\n>>> f.append({'a': 1, 'b': 2})\n>>> f.append(Record(Symbol('label'), ['field1', ['field2item1', 'field2item2']]))\n>>> print(f.contents())\n{\"a\": 1 \"b\": 2} <label \"field1\" [\"field2item1\" \"field2item2\"]>\n\n>>> f = Formatter(indent=4)\n>>> f.append({'a': 1, 'b': 2})\n>>> f.append(Record(Symbol('label'), ['field1', ['field2item1', 'field2item2']]))\n>>> print(f.contents())\n{\n    \"a\": 1\n    \"b\": 2\n}\n<label \"field1\" [\n    \"field2item1\"\n    \"field2item2\"\n]>\n

Parameters:

Name Type Description Default format_embedded

function accepting an Embedded.embeddedValue and returning a Value for serialization.

lambda x: x indent int | None

None disables indented pretty-printing; otherwise, an int specifies indentation per nesting-level.

None with_commas bool

True causes commas to separate sequence and set items and dictionary entries; False omits commas.

False trailing_comma bool

True causes a comma to be printed after the final item or entry in a sequence, set or dictionary; False omits this trailing comma

False include_annotations bool

True causes annotations to be included in the output; False causes them to be omitted.

True

Attributes:

Name Type Description indent_delta int

indentation per nesting-level

chunks list[str]

fragments of output

Source code in preserves/text.py
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
"},{"location":"text/#preserves.text.Formatter.append","title":"append(v)","text":"

Extend self.chunks with at least one chunk, together making up the text representation of v.

Source code in preserves/text.py
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
"},{"location":"text/#preserves.text.Formatter.contents","title":"contents()","text":"

Returns a str constructed from the join of the chunks in self.chunks.

Source code in preserves/text.py
def contents(self):\n\"\"\"Returns a `str` constructed from the join of the chunks in `self.chunks`.\"\"\"\n    return u''.join(self.chunks)\n
"},{"location":"text/#preserves.text.Formatter.is_indenting","title":"is_indenting()","text":"

Returns True iff this Formatter is in pretty-printing indenting mode.

Source code in preserves/text.py
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 > 0\n
"},{"location":"text/#preserves.text.Parser","title":"Parser(input_buffer='', include_annotations=False, parse_embedded=lambda x: x)","text":"

Bases: TextCodec

Parser for the human-readable Preserves text syntax.

Parameters:

Name Type Description Default input_buffer str

initial contents of the input buffer; may subsequently be extended by calling extend.

'' include_annotations bool

if True, wrap each value and subvalue in an Annotated object.

False parse_embedded

function accepting a Value and returning a possibly-decoded form of that value suitable for placing into an Embedded object.

lambda x: x

Normal usage is to supply input text, and keep calling next until a ShortPacket exception is raised:

>>> d = Parser('123 \"hello\" @x []')\n>>> d.next()\n123\n>>> d.next()\n'hello'\n>>> d.next()\n()\n>>> d.next()\nTraceback (most recent call last):\n  ...\npreserves.error.ShortPacket: Short input buffer\n

Alternatively, keep calling try_next until it yields None, which is not in the domain of Preserves Values:

>>> d = Parser('123 \"hello\" @x []')\n>>> d.try_next()\n123\n>>> d.try_next()\n'hello'\n>>> d.try_next()\n()\n>>> d.try_next()\n

For convenience, Parser implements the iterator interface, backing it with try_next, so you can simply iterate over all complete values in an input:

>>> d = Parser('123 \"hello\" @x []')\n>>> list(d)\n[123, 'hello', ()]\n
>>> for v in Parser('123 \"hello\" @x []'):\n...     print(repr(v))\n123\n'hello'\n()\n

Supply include_annotations=True to read annotations alongside the annotated values:

>>> d = Parser('123 \"hello\" @x []', include_annotations=True)\n>>> list(d)\n[123, 'hello', @#x ()]\n

If you are incrementally reading from, say, a socket, you can use extend to add new input as if comes available:

>>> d = Parser('123 \"he')\n>>> d.try_next()\n123\n>>> d.try_next() # returns None because the input is incomplete\n>>> d.extend('llo\"')\n>>> d.try_next()\n'hello'\n>>> d.try_next()\n

Attributes:

Name Type Description input_buffer str

buffered input waiting to be processed

index int

read position within input_buffer

Source code in preserves/text.py
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
"},{"location":"text/#preserves.text.Parser.extend","title":"extend(text)","text":"

Appends text to the remaining contents of self.input_buffer, trimming already-processed text from the front of self.input_buffer and resetting self.index to zero.

Source code in preserves/text.py
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
"},{"location":"text/#preserves.text.Parser.next","title":"next()","text":"

Reads the next complete Value from the internal buffer, raising ShortPacket if too few bytes are available, or DecodeError if the input is invalid somehow.

Source code in preserves/text.py
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 == '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            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 == '<':\n        self.skip()\n        vs = self.upto('>', 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 '>]},':\n        raise DecodeError('Unexpected ' + c)\n    self.skip()\n    return self.wrap(self.read_raw_symbol_or_number([c]))\n
"},{"location":"text/#preserves.text.Parser.try_next","title":"try_next()","text":"

Like next, but returns None instead of raising ShortPacket.

Source code in preserves/text.py
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
"},{"location":"text/#preserves.text.parse","title":"parse(text, **kwargs)","text":"

Yields the first complete encoded value from text, passing kwargs through to the Parser constructor. Raises exceptions as per next.

Parameters:

Name Type Description Default text str

encoded data to decode

required Source code in preserves/text.py
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
"},{"location":"text/#preserves.text.parse_with_annotations","title":"parse_with_annotations(bs, **kwargs)","text":"

Like parse, but supplying include_annotations=True to the Parser constructor.

Source code in preserves/text.py
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
"},{"location":"text/#preserves.text.stringify","title":"stringify(v, **kwargs)","text":"

Convert a single Value v to a string. Any supplied kwargs are passed on to the underlying Formatter constructor.

Source code in preserves/text.py
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
"},{"location":"values/","title":"Representations of Values","text":"

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.

Python's lists and tuples correspond to Preserves Sequences, and dicts and sets to Dictionary and Set values, respectively. Preserves Records are represented by Record objects. Finally, embedded values are represented by Embedded objects.

The preserves.values module implements the core representations of Preserves Values as Python values.

"},{"location":"values/#preserves.values.Annotated","title":"Annotated(item)","text":"

Bases: object

A Preserves Value along with a sequence of Values annotating it. Compares equal to the underlying Value, ignoring the annotations. See the specification document for more about annotations.

>>> import preserves\n>>> a = preserves.parse('''\n... # A comment\n... [1 2 3]\n... ''', include_annotations=True)\n>>> a\n@'A comment' (1, 2, 3)\n>>> a.item\n(1, 2, 3)\n>>> a.annotations\n['A comment']\n>>> a == (1, 2, 3)\nTrue\n>>> a == preserves.parse('@xyz [1 2 3]', include_annotations=True)\nTrue\n>>> a[0]\nTraceback (most recent call last):\n  ...\nTypeError: 'Annotated' object is not subscriptable\n>>> a.item[0]\n1\n>>> type(a.item[0])\n<class 'preserves.values.Annotated'>\n>>> a.item[0].annotations\n[]\n>>> print(preserves.stringify(a))\n@\"A comment\" [1 2 3]\n>>> print(preserves.stringify(a, include_annotations=False))\n[1 2 3]\n

Attributes:

Name Type Description item Value

the underlying annotated Value

annotations list[Value]

the annotations attached to self.item

Source code in preserves/values.py
def __init__(self, item):\n    self.annotations = []\n    self.item = item\n
"},{"location":"values/#preserves.values.Annotated.peel","title":"peel()","text":"

Calls strip_annotations on self with depth=1.

Source code in preserves/values.py
def peel(self):\n\"\"\"Calls [strip_annotations][preserves.values.strip_annotations] on `self` with `depth=1`.\"\"\"\n    return strip_annotations(self, 1)\n
"},{"location":"values/#preserves.values.Annotated.strip","title":"strip(depth=inf)","text":"

Calls strip_annotations on self and depth.

Source code in preserves/values.py
def strip(self, depth=inf):\n\"\"\"Calls [strip_annotations][preserves.values.strip_annotations] on `self` and `depth`.\"\"\"\n    return strip_annotations(self, depth)\n
"},{"location":"values/#preserves.values.Embedded","title":"Embedded(embeddedValue)","text":"

Representation of a Preserves Embedded value. For more on the meaning and use of embedded values, see the specification.

>>> import io\n>>> e = Embedded(io.StringIO('some text'))\n>>> e                                        # doctest: +ELLIPSIS\n#!<_io.StringIO object at ...>\n>>> e.embeddedValue                          # doctest: +ELLIPSIS\n<_io.StringIO object at ...>\n
>>> import preserves\n>>> print(preserves.stringify(Embedded(None)))\nTraceback (most recent call last):\n  ...\nTypeError: Cannot preserves-format: None\n>>> print(preserves.stringify(Embedded(None), format_embedded=lambda x: 'abcdef'))\n#!\"abcdef\"\n

Attributes:

Name Type Description embeddedValue

any Python value; could be a platform object, could be a representation of a Preserves Value, could be None, could be anything!

Source code in preserves/values.py
def __init__(self, embeddedValue):\n    self.embeddedValue = embeddedValue\n
"},{"location":"values/#preserves.values.Float","title":"Float(value)","text":"

Bases: object

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.)

>>> Float(3.45)\nFloat(3.45)\n>>> import preserves\n>>> preserves.stringify(Float(3.45))\n'3.45f'\n>>> preserves.stringify(3.45)\n'3.45'\n>>> preserves.parse('3.45f')\nFloat(3.45)\n>>> preserves.parse('3.45')\n3.45\n>>> preserves.encode(Float(3.45))\nb'\\x87\\x04@\\\\\\xcc\\xcd'\n>>> preserves.encode(3.45)\nb'\\x87\\x08@\\x0b\\x99\\x99\\x99\\x99\\x99\\x9a'\n

Attributes:

Name Type Description value float

the double-precision representation of intended single-precision value

Source code in preserves/values.py
def __init__(self, value):\n    self.value = value\n
"},{"location":"values/#preserves.values.Float.from_bytes","title":"from_bytes(bs) staticmethod","text":"

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 struct.unpack('>f', ...) equivalent.

>>> Float.from_bytes(b'\\x7f\\x80\\x00{')\nFloat(nan)\n>>> Float.from_bytes(b'\\x7f\\x80\\x00{').to_bytes()\nb'\\x7f\\x80\\x00{'\n\n>>> struct.unpack('>f', b'\\x7f\\x80\\x00{')[0]\nnan\n>>> Float(struct.unpack('>f', b'\\x7f\\x80\\x00{')[0]).to_bytes()\nb'\\x7f\\xc0\\x00{'\n>>> struct.pack('>f', struct.unpack('>f', b'\\x7f\\x80\\x00{')[0])\nb'\\x7f\\xc0\\x00{'\n

(Note well the difference between 7f80007b and 7fc0007b!)

Source code in preserves/values.py
@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('>f', ...)`\n    equivalent.\n\n    ```python\n    >>> Float.from_bytes(b'\\\\x7f\\\\x80\\\\x00{')\n    Float(nan)\n    >>> Float.from_bytes(b'\\\\x7f\\\\x80\\\\x00{').to_bytes()\n    b'\\\\x7f\\\\x80\\\\x00{'\n\n    >>> struct.unpack('>f', b'\\\\x7f\\\\x80\\\\x00{')[0]\n    nan\n    >>> Float(struct.unpack('>f', b'\\\\x7f\\\\x80\\\\x00{')[0]).to_bytes()\n    b'\\\\x7f\\\\xc0\\\\x00{'\n    >>> struct.pack('>f', struct.unpack('>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('>I', bs)[0]\n    if (vf & 0x7f800000) == 0x7f800000:\n        # NaN or inf. Preserve quiet/signalling bit by manually expanding to double-precision.\n        sign = vf >> 31\n        payload = vf & 0x007fffff\n        dbs = struct.pack('>Q', (sign << 63) | 0x7ff0000000000000 | (payload << 29))\n        return Float(struct.unpack('>d', dbs)[0])\n    else:\n        return Float(struct.unpack('>f', bs)[0])\n
"},{"location":"values/#preserves.values.Float.to_bytes","title":"to_bytes()","text":"

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 struct.pack('>f', ...) equivalent.

>>> Float.from_bytes(b'\\x7f\\x80\\x00{')\nFloat(nan)\n>>> Float.from_bytes(b'\\x7f\\x80\\x00{').to_bytes()\nb'\\x7f\\x80\\x00{'\n\n>>> struct.unpack('>f', b'\\x7f\\x80\\x00{')[0]\nnan\n>>> Float(struct.unpack('>f', b'\\x7f\\x80\\x00{')[0]).to_bytes()\nb'\\x7f\\xc0\\x00{'\n>>> struct.pack('>f', struct.unpack('>f', b'\\x7f\\x80\\x00{')[0])\nb'\\x7f\\xc0\\x00{'\n

(Note well the difference between 7f80007b and 7fc0007b!)

Source code in preserves/values.py
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('>f', ...)` equivalent.\n\n    ```python\n    >>> Float.from_bytes(b'\\\\x7f\\\\x80\\\\x00{')\n    Float(nan)\n    >>> Float.from_bytes(b'\\\\x7f\\\\x80\\\\x00{').to_bytes()\n    b'\\\\x7f\\\\x80\\\\x00{'\n\n    >>> struct.unpack('>f', b'\\\\x7f\\\\x80\\\\x00{')[0]\n    nan\n    >>> Float(struct.unpack('>f', b'\\\\x7f\\\\x80\\\\x00{')[0]).to_bytes()\n    b'\\\\x7f\\\\xc0\\\\x00{'\n    >>> struct.pack('>f', struct.unpack('>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('>d', self.value)\n        vd = struct.unpack('>Q', dbs)[0]\n        sign = vd >> 63\n        payload = (vd >> 29) & 0x007fffff\n        vf = (sign << 31) | 0x7f800000 | payload\n        return struct.pack('>I', vf)\n    else:\n        return struct.pack('>f', self.value)\n
"},{"location":"values/#preserves.values.ImmutableDict","title":"ImmutableDict(*args, **kwargs)","text":"

Bases: dict

A subclass of Python's built-in dict that overrides methods that could mutate the dictionary, causing them to raise TypeError('Immutable') if called.

Implements the __hash__ method, allowing ImmutableDict instances to be used whereever immutable data are permitted; in particular, as keys in other dictionaries.

>>> d = ImmutableDict([('a', 1), ('b', 2)])\n>>> d\n{'a': 1, 'b': 2}\n>>> d['c'] = 3\nTraceback (most recent call last):\n  ...\nTypeError: Immutable\n>>> del d['b']\nTraceback (most recent call last):\n  ...\nTypeError: Immutable\n
Source code in preserves/values.py
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
"},{"location":"values/#preserves.values.ImmutableDict.from_kvs","title":"from_kvs(kvs) staticmethod","text":"

Constructs an ImmutableDict from a sequence of alternating keys and values; compare to the ImmutableDict constructor, which takes a sequence of key-value pairs.

>>> ImmutableDict.from_kvs(['a', 1, 'b', 2])\n{'a': 1, 'b': 2}\n>>> ImmutableDict.from_kvs(['a', 1, 'b', 2])['c'] = 3\nTraceback (most recent call last):\n  ...\nTypeError: Immutable\n
Source code in preserves/values.py
@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    >>> ImmutableDict.from_kvs(['a', 1, 'b', 2])\n    {'a': 1, 'b': 2}\n    >>> 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
"},{"location":"values/#preserves.values.Record","title":"Record(key, fields)","text":"

Bases: object

Representation of Preserves Records, which are a pair of a label Value and a sequence of field Values.

>>> r = Record(Symbol('label'), ['field1', ['field2item1', 'field2item2']])\n>>> r\n#label('field1', ['field2item1', 'field2item2'])\n>>> r.key\n#label\n>>> r.fields\n('field1', ['field2item1', 'field2item2'])\n>>> import preserves\n>>> preserves.stringify(r)\n'<label \"field1\" [\"field2item1\" \"field2item2\"]>'\n>>> r == preserves.parse('<label \"field1\" [\"field2item1\" \"field2item2\"]>')\nTrue\n

Parameters:

Name Type Description Default key Value

the Record's label

required fields iterable[Value]

the fields of the Record

required

Attributes:

Name Type Description key Value

the Record's label

fields tuple[Value]

the fields of the Record

Source code in preserves/values.py
def __init__(self, key, fields):\n    self.key = key\n    self.fields = tuple(fields)\n    self.__hash = None\n
"},{"location":"values/#preserves.values.Record.makeBasicConstructor","title":"makeBasicConstructor(label, fieldNames) staticmethod","text":"

Constructs and returns a \"constructor\" for Records having a certain label and number of fields.

Deprecated

Use preserves.schema definitions instead.

The \"constructor\" is a callable function that accepts len(fields) arguments and returns a Record with label as its label and the arguments to the constructor as field values.

In addition, the \"constructor\" has a constructorInfo attribute holding a RecordConstructorInfo object, an isClassOf attribute holding a unary function that returns True iff its argument is a Record with label label and arity len(fieldNames), and an ensureClassOf attribute that raises an Exception if isClassOf returns false on its argument and returns the argument otherwise.

Finally, for each field name f in fieldNames, the \"constructor\" object has an attribute _f that is a unary function that retrieves the f field from the passed in argument.

>>> c = Record.makeBasicConstructor(Symbol('date'), 'year month day')\n>>> c(1969, 7, 16)\n#date(1969, 7, 16)\n>>> c.constructorInfo\n#date/3\n>>> c.isClassOf(c(1969, 7, 16))\nTrue\n>>> c.isClassOf(Record(Symbol('date'), [1969, 7, 16]))\nTrue\n>>> c.isClassOf(Record(Symbol('date'), [1969]))\nFalse\n>>> c.ensureClassOf(c(1969, 7, 16))\n#date(1969, 7, 16)\n>>> c.ensureClassOf(Record(Symbol('date'), [1969]))\nTraceback (most recent call last):\n  ...\nTypeError: Record: expected #date/3, got #date(1969)\n>>> c._year(c(1969, 7, 16))\n1969\n>>> c._month(c(1969, 7, 16))\n7\n>>> c._day(c(1969, 7, 16))\n16\n

Parameters:

Name Type Description Default label Value

Label to use for constructed/matched Records

required fieldNames tuple[str] | list[str] | str

Names of the Record's fields

required Source code in preserves/values.py
@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    >>> c = Record.makeBasicConstructor(Symbol('date'), 'year month day')\n    >>> c(1969, 7, 16)\n    #date(1969, 7, 16)\n    >>> c.constructorInfo\n    #date/3\n    >>> c.isClassOf(c(1969, 7, 16))\n    True\n    >>> c.isClassOf(Record(Symbol('date'), [1969, 7, 16]))\n    True\n    >>> c.isClassOf(Record(Symbol('date'), [1969]))\n    False\n    >>> c.ensureClassOf(c(1969, 7, 16))\n    #date(1969, 7, 16)\n    >>> c.ensureClassOf(Record(Symbol('date'), [1969]))\n    Traceback (most recent call last):\n      ...\n    TypeError: Record: expected #date/3, got #date(1969)\n    >>> c._year(c(1969, 7, 16))\n    1969\n    >>> c._month(c(1969, 7, 16))\n    7\n    >>> 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
"},{"location":"values/#preserves.values.Record.makeConstructor","title":"makeConstructor(labelSymbolText, fieldNames) staticmethod","text":"

Equivalent to Record.makeBasicConstructor(Symbol(labelSymbolText), fieldNames).

Deprecated

Use preserves.schema definitions instead.

Source code in preserves/values.py
@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
"},{"location":"values/#preserves.values.RecordConstructorInfo","title":"RecordConstructorInfo(key, arity)","text":"

Bases: object

Describes the shape of a Record constructor, namely its label and its arity (field count).

>>> RecordConstructorInfo(Symbol('label'), 3)\n#label/3\n

Attributes:

Name Type Description key Value

the label of matching Records

arity int

the number of fields in matching Records

Source code in preserves/values.py
def __init__(self, key, arity):\n    self.key = key\n    self.arity = arity\n
"},{"location":"values/#preserves.values.Symbol","title":"Symbol(name)","text":"

Bases: object

Representation of Preserves Symbols.

>>> Symbol('xyz')\n#xyz\n>>> Symbol('xyz').name\n'xyz'\n>>> import preserves\n>>> preserves.stringify(Symbol('xyz'))\n'xyz'\n>>> preserves.stringify(Symbol('hello world'))\n'|hello world|'\n>>> preserves.parse('xyz')\n#xyz\n>>> preserves.parse('|hello world|')\n#hello world\n

Attributes:

Name Type Description name str | Symbol

The symbol's text label. If an existing Symbol is passed in, the existing Symbol's name is used as the name for the new Symbol.

Source code in preserves/values.py
def __init__(self, name):\n    self.name = name.name if isinstance(name, Symbol) else name\n
"},{"location":"values/#preserves.values.annotate","title":"annotate(v, *anns)","text":"

Wraps v in an Annotated object, if it isn't already wrapped, and appends each of the anns to the Annotated's annotations sequence. NOTE: Does not recursively ensure that any parts of the argument v are themselves wrapped in Annotated objects!

>>> import preserves\n>>> print(preserves.stringify(annotate(123, \"A comment\", \"Another comment\")))\n@\"A comment\" @\"Another comment\" 123\n
Source code in preserves/values.py
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    >>> import preserves\n    >>> 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
"},{"location":"values/#preserves.values.cmp_floats","title":"cmp_floats(a, b)","text":"

Implements the totalOrder predicate defined in section 5.10 of IEEE Std 754-2008.

Source code in preserves/values.py
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 & 0x8000000000000000: a = a ^ 0x7fffffffffffffff\n    if b & 0x8000000000000000: b = b ^ 0x7fffffffffffffff\n    return a - b\n
"},{"location":"values/#preserves.values.dict_kvs","title":"dict_kvs(d)","text":"

Generator function yielding a sequence of alternating keys and values from d. In some sense the inverse of ImmutableDict.from_kvs.

>>> list(dict_kvs({'a': 1, 'b': 2}))\n['a', 1, 'b', 2]\n
Source code in preserves/values.py
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    >>> 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
"},{"location":"values/#preserves.values.is_annotated","title":"is_annotated(v)","text":"

True iff v is an instance of Annotated.

Source code in preserves/values.py
def is_annotated(v):\n\"\"\"`True` iff `v` is an instance of [Annotated][preserves.values.Annotated].\"\"\"\n    return isinstance(v, Annotated)\n
"},{"location":"values/#preserves.values.preserve","title":"preserve(v)","text":"

Converts v to a representation of a Preserves Value by (repeatedly) setting

v = v.__preserve__()\n

while v has a __preserve__ method. Parsed Schema values are able to render themselves to their serialized representations this way.

Source code in preserves/values.py
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
"},{"location":"values/#preserves.values.strip_annotations","title":"strip_annotations(v, depth=inf)","text":"

Exposes depth layers of raw structure of potentially-Annotated Values. If depth==0 or v is not Annotated, just returns v. Otherwise, descends recursively into the structure of v.item.

>>> import preserves\n>>> a = preserves.parse('@\"A comment\" [@a 1 @b 2 @c 3]', include_annotations=True)\n>>> is_annotated(a)\nTrue\n>>> print(preserves.stringify(a))\n@\"A comment\" [@a 1 @b 2 @c 3]\n>>> print(preserves.stringify(strip_annotations(a)))\n[1 2 3]\n>>> print(preserves.stringify(strip_annotations(a, depth=1)))\n[@a 1 @b 2 @c 3]\n
Source code in preserves/values.py
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    >>> import preserves\n    >>> a = preserves.parse('@\"A comment\" [@a 1 @b 2 @c 3]', include_annotations=True)\n    >>> is_annotated(a)\n    True\n    >>> print(preserves.stringify(a))\n    @\"A comment\" [@a 1 @b 2 @c 3]\n    >>> print(preserves.stringify(strip_annotations(a)))\n    [1 2 3]\n    >>> 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
"}]} \ No newline at end of file diff --git a/python/0.992.0/sitemap.xml b/python/0.992.0/sitemap.xml new file mode 100644 index 0000000..4cc9e8e --- /dev/null +++ b/python/0.992.0/sitemap.xml @@ -0,0 +1,58 @@ + + + + https://preserves.dev/python/latest/ + 2023-11-01 + daily + + + https://preserves.dev/python/latest/api/ + 2023-11-01 + daily + + + https://preserves.dev/python/latest/binary/ + 2023-11-01 + daily + + + https://preserves.dev/python/latest/compare/ + 2023-11-01 + daily + + + https://preserves.dev/python/latest/error/ + 2023-11-01 + daily + + + https://preserves.dev/python/latest/fold/ + 2023-11-01 + daily + + + https://preserves.dev/python/latest/merge/ + 2023-11-01 + daily + + + https://preserves.dev/python/latest/path/ + 2023-11-01 + daily + + + https://preserves.dev/python/latest/schema/ + 2023-11-01 + daily + + + https://preserves.dev/python/latest/text/ + 2023-11-01 + daily + + + https://preserves.dev/python/latest/values/ + 2023-11-01 + daily + + \ No newline at end of file diff --git a/python/0.992.0/syndicate-protocols-schema-bundle.bin b/python/0.992.0/syndicate-protocols-schema-bundle.bin new file mode 100644 index 0000000..3fe50c6 --- /dev/null +++ b/python/0.992.0/syndicate-protocols-schema-bundle.bin @@ -0,0 +1,40 @@ +bundletcpschemaversion definitionsTcpLocalreclit tcp-localtuplenamedhostatomStringnamedportatom SignedInteger TcpRemotereclit +tcp-remotetuplenamedhostatomStringnamedportatom SignedInteger TcpPeerInforeclittcp-peertuplenamedhandleembeddedanynamedlocalrefTcpLocalnamedremoteref TcpRemote embeddedTyperef EntityRefCaphttpschemaversion definitionsChunkorstringatomStringbytesatom +ByteStringHeadersdictofatomSymbolatomStringMimeTypeatomSymbol +QueryValueorstringatomStringfilereclitfiletuplenamedfilenameatomStringnamedheadersrefHeadersnamedbodyatom +ByteString HostPatternorhostatomStringanylit HttpBindingreclit http-bindtuplenamedhostref HostPatternnamedportatom SignedIntegernamedmethodref MethodPatternnamedpathref PathPatternnamedhandlerembeddedref HttpRequest HttpContextreclitrequesttuplenamedreqref HttpRequestnamedresembeddedref HttpResponse HttpRequestreclit http-requesttuplenamedsequenceNumberatom SignedIntegernamedhostatomStringnamedportatom SignedIntegernamedmethodatomSymbolnamedpathseqofatomStringnamedheadersrefHeadersnamedquerydictofatomSymbolseqofref +QueryValuenamedbodyref RequestBody HttpServicereclit http-servicetuplenamedhostref HostPatternnamedportatom SignedIntegernamedmethodref MethodPatternnamedpathref PathPattern PathPatternseqofrefPathPatternElement RequestBodyorpresentatom +ByteStringabsentlit HttpListenerreclit http-listenertuplenamedportatom SignedInteger HttpResponseorstatusreclitstatustuplenamedcodeatom SignedIntegernamedmessageatomStringheaderreclitheadertuplenamednameatomSymbolnamedvalueatomStringchunkreclitchunktuplenamedchunkrefChunkdonereclitdonetuplenamedchunkrefChunk MethodPatternoranylitspecificatomSymbolPathPatternElementorlabelatomStringwildcardlit_restlit... embeddedTypenoiseschemaversion definitionsPacketorcompleteatom +ByteString +fragmentedseqofatom +ByteString NoiseSpecanddictkeynamedkeyatom +ByteStringservicenamedservicerefServiceSelectornamedprotocolref NoiseProtocolnamed preSharedKeysrefNoisePreSharedKeys NoiseProtocolorpresentdictprotocolnamedprotocolatomStringinvaliddictprotocolnamedprotocolanyabsentdict NoiseStepTypelitnoiseSecretKeyFieldorpresentdict secretKeynamed secretKeyatom +ByteStringinvaliddict secretKeynamed secretKeyanyabsentdictDefaultProtocollit!Noise_NK_25519_ChaChaPoly_BLAKE2sNoiseStepDetailrefServiceSelectorServiceSelectoranyNoiseServiceSpecandnamedbaseref NoiseSpecnamed secretKeyrefSecretKeyFieldNoisePreSharedKeysorpresentdict preSharedKeysnamed preSharedKeysseqofatom +ByteStringinvaliddict preSharedKeysnamed preSharedKeysanyabsentdictNoisePathStepDetailref NoiseSpecNoiseDescriptionDetailrefNoiseServiceSpec embeddedTypetimerschemaversion definitionsSetTimerreclit set-timertuplenamedlabelanynamedsecondsatomDoublenamedkindref TimerKind LaterThanreclit +later-thantuplenamedsecondsatomDouble TimerKindorrelativelitrelativeabsolutelitabsoluteclearlitclear TimerExpiredreclit timer-expiredtuplenamedlabelanynamedsecondsatomDouble embeddedTypetraceschemaversion definitionsOidanyNameor anonymousreclit anonymoustuplenamedreclitnamedtuplenamednameanyTargetreclitentitytuplenamedactorrefActorIdnamedfacetrefFacetIdnamedoidrefOidTaskIdanyTurnIdanyActorIdanyFacetIdany TurnCauseorturnreclit caused-bytuplenamedidrefTurnIdcleanupreclitcleanuptuplelinkedTaskReleasereclitlinked-task-releasetuplenamedidrefTaskIdnamedreasonrefLinkedTaskReleaseReasonperiodicActivationreclitperiodic-activationtuplenamedperiodatomDoubledelayreclitdelaytuplenamed causingTurnrefTurnIdnamedamountatomDoubleexternalreclitexternaltuplenamed descriptionany TurnEventorassertreclitasserttuplenamed assertionrefAssertionDescriptionnamedhandlerefprotocolHandleretractreclitretracttuplenamedhandlerefprotocolHandlemessagereclitmessagetuplenamedbodyrefAssertionDescriptionsyncreclitsynctuplenamedpeerrefTarget breakLinkreclit +break-linktuplenamedsourcerefActorIdnamedhandlerefprotocolHandle +ExitStatusoroklitokErrorrefprotocolError +TraceEntryreclittracetuplenamed timestampatomDoublenamedactorrefActorIdnameditemrefActorActivationActorActivationorstartreclitstarttuplenamed actorNamerefNameturnrefTurnDescriptionstopreclitstoptuplenamedstatusref +ExitStatusFacetStopReasonorexplicitActionlitexplicit-actioninertlitinertparentStoppinglitparent-stopping actorStoppinglitactor-stoppingTurnDescriptionreclitturntuplenamedidrefTurnIdnamedcauseref TurnCausenamedactionsseqofrefActionDescriptionActionDescriptionordequeuereclitdequeuetuplenamedeventrefTargetedTurnEventenqueuereclitenqueuetuplenamedeventrefTargetedTurnEventdequeueInternalreclitdequeue-internaltuplenamedeventrefTargetedTurnEventenqueueInternalreclitenqueue-internaltuplenamedeventrefTargetedTurnEventspawnreclitspawntuplenamedlinkatomBooleannamedidrefActorIdlinkreclitlinktuplenamed parentActorrefActorIdnamed childToParentrefprotocolHandlenamed +childActorrefActorIdnamed parentToChildrefprotocolHandle +facetStartreclit facet-starttuplenamedpathseqofrefFacetId facetStopreclit +facet-stoptuplenamedpathseqofrefFacetIdnamedreasonrefFacetStopReasonlinkedTaskStartreclitlinked-task-starttuplenamedtaskNamerefNamenamedidrefTaskIdTargetedTurnEventrecliteventtuplenamedtargetrefTargetnameddetailref TurnEventAssertionDescriptionorvaluereclitvaluetuplenamedvalueanyopaquereclitopaquetuplenamed descriptionanyLinkedTaskReleaseReasonor cancelledlit cancellednormallitnormal embeddedTyperef EntityRefCapstreamschemaversion definitionsModeorbyteslitbyteslinesrefLineModepacketreclitpackettuplenamedsizeatom SignedIntegerobjectreclitobjecttuplenamed descriptionanySinkorsourcereclitsourcetuplenamed +controllerembeddedrefSource StreamErrorref StreamErrordatareclitdatatuplenamedpayloadanynamedmoderefModeeofrecliteoftupleSourceorsinkreclitsinktuplenamed +controllerembeddedrefSink StreamErrorref StreamErrorcreditreclitcredittuplenamedamountref CreditAmountnamedmoderefModeLineModeorlflitlfcrlflitcrlf StreamErrorrecliterrortuplenamedmessageatomString CreditAmountorcountatom SignedInteger unboundedlit unboundedStreamConnectionreclitstream-connectiontuplenamedsourceembeddedrefSourcenamedsinkembeddedrefSinknamedspecanyStreamListenerErrorreclitstream-listener-errortuplenamedspecanynamedmessageatomStringStreamListenerReadyreclitstream-listener-readytuplenamedspecany embeddedTyperef EntityRefCapsturdyschemaversion definitionsLitreclitlittuplenamedvalueanyOidatom SignedIntegerAltsreclitortuplenamed alternativesseqofrefRewritePAndreclitandtuplenamedpatternsseqofrefPatternPNotreclitnottuplenamedpatternrefPatternTRefreclitreftuplenamedbindingatom SignedIntegerPAtomorBooleanlitBooleanFloatlitFloatDoublelitDouble SignedIntegerlit SignedIntegerStringlitString +ByteStringlit +ByteStringSymbollitSymbolPBindreclitbindtuplenamedpatternrefPatternCaveatorRewriterefRewriteAltsrefAltsRejectrefRejectunknownanyRejectreclitrejecttuplenamedpatternrefPatternPatternorPDiscardrefPDiscardPAtomrefPAtom PEmbeddedref PEmbeddedPBindrefPBindPAndrefPAndPNotrefPNotLitrefLit PCompoundref PCompoundRewritereclitrewritetuplenamedpatternrefPatternnamedtemplaterefTemplateWireReforminetuplelitnamedoidrefOidyours tuplePrefixlitnamedoidrefOidnamed attenuationseqofrefCaveatPDiscardreclit_tupleTemplateor +TAttenuateref +TAttenuateTRefrefTRefLitrefLit TCompoundref TCompound PCompoundorrecreclitrectuplenamedlabelanynamedfieldsseqofrefPatternarrreclitarrtuplenameditemsseqofrefPatterndictreclitdicttuplenamedentriesdictofanyrefPattern PEmbeddedlitEmbedded SturdyRefreclitreftuplenamed +parametersref +Parameters TCompoundorrecreclitrectuplenamedlabelanynamedfieldsseqofrefTemplatearrreclitarrtuplenameditemsseqofrefTemplatedictreclitdicttuplenamedentriesdictofanyrefTemplate +Parametersanddictoidnamedoidanysignamedsigatom +ByteStringnamedcaveatsref CaveatsField +TAttenuatereclit attenuatetuplenamedtemplaterefTemplatenamed attenuationseqofrefCaveat CaveatsFieldorpresentdictcaveatsnamedcaveatsseqofrefCaveatinvaliddictcaveatsnamedcaveatsanyabsentdictSturdyStepTypelitrefSturdyStepDetailref +ParametersSturdyPathStepDetailref +ParametersSturdyDescriptionDetaildictkeynamedkeyatom +ByteStringoidnamedoidany embeddedTyperef EntityRefCapworkerschemaversion definitionsInstancereclitInstancetuplenamednameatomStringnamedargumentany embeddedTyperef EntityRefCapserviceschemaversion definitionsStateorstartedlitstartedreadylitreadyfailedlitfailedcompletelitcomplete userDefinedany +RunServicereclit run-servicetuplenamed serviceNameany ServiceStatereclit service-statetuplenamed serviceNameanynamedstaterefState ServiceObjectreclitservice-objecttuplenamed serviceNameanynamedobjectanyRequireServicereclitrequire-servicetuplenamed serviceNameanyRestartServicereclitrestart-servicetuplenamed serviceNameanyServiceDependencyreclit +depends-ontuplenameddependeranynameddependeeref ServiceState embeddedTyperef EntityRefCapprotocolschemaversion definitionsOidatom SignedIntegerSyncreclitsynctuplenamedpeerembeddedlitTurnseqofref TurnEventErrorrecliterrortuplenamedmessageatomStringnameddetailanyEventorAssertrefAssertRetractrefRetractMessagerefMessageSyncrefSyncAssertreclitasserttuplenamed assertionref AssertionnamedhandlerefHandleHandleatom SignedIntegerPacketorTurnrefTurnErrorrefError Extensionref ExtensionMessagereclitmessagetuplenamedbodyref AssertionRetractreclitretracttuplenamedhandlerefHandle Assertionany Extensionrecnamedlabelanynamedfieldsseqofany TurnEventtuplenamedoidrefOidnamedeventrefEvent embeddedType dataspaceschemaversion definitionsObservereclitObservetuplenamedpatternrefdataspacePatternsPatternnamedobserverembeddedany embeddedTyperef EntityRefCap +gatekeeperschemaversion definitionsBindreclitbindtuplenamed descriptionref Descriptionnamedtargetembeddedanynamedobserverref BindObserverSteprecnamedstepTypeatomSymboltuplenameddetailanyBoundorboundreclitboundtuplenamedpathSteprefPathStepRejectedrefRejectedRoutereclitroute tuplePrefixnamed +transportsseqofanynamed pathStepsseqofrefPathStepResolvereclitresolvetuplenamedsteprefStepnamedobserverembeddedrefResolvedPathSteprecnamedstepTypeatomSymboltuplenameddetailanyRejectedreclitrejectedtuplenameddetailanyResolvedoracceptedreclitacceptedtuplenamedresponderSessionembeddedanyRejectedrefRejected DescriptionrecnamedstepTypeatomSymboltuplenameddetailany ResolvePathreclit resolve-pathtuplenamedrouterefRoutenamedaddranynamedcontrolembeddedrefTransportControlnamedresolvedrefResolved BindObserverorpresentembeddedrefBoundabsentlitForceDisconnectreclitforce-disconnecttupleResolvedPathStepreclit path-steptuplenamedoriginembeddedrefResolvenamedpathSteprefPathStepnamedresolvedrefResolvedTransportControlrefForceDisconnectTransportConnectionreclitconnect-transporttuplenamedaddranynamedcontrolembeddedrefTransportControlnamedresolvedrefResolved embeddedTyperef EntityRefCaptransportAddressschemaversion definitionsTcpreclittcptuplenamedhostatomStringnamedportatom SignedIntegerUnixreclitunixtuplenamedpathatomStringStdioreclitstdiotuple WebSocketreclitwstuplenamedurlatomString embeddedTypedataspacePatternsschemaversion definitionsDLitreclitlittuplenamedvaluerefAnyAtomDBindreclitbindtuplenamedpatternrefPatternAnyAtomorboolatomBooleanfloatatomFloatdoubleatomDoubleintatom SignedIntegerstringatomStringbytesatom +ByteStringsymbolatomSymbolembeddedembeddedanyPatternorDDiscardrefDDiscardDBindrefDBindDLitrefDLit DCompoundref DCompoundDDiscardreclit_tuple DCompoundorrecreclitrectuplenamedlabelanynamedfieldsseqofrefPatternarrreclitarrtuplenameditemsseqofrefPatterndictreclitdicttuplenamedentriesdictofanyrefPattern embeddedTyperef EntityRefCap \ No newline at end of file diff --git a/python/0.992.0/text/index.html b/python/0.992.0/text/index.html new file mode 100644 index 0000000..6839f33 --- /dev/null +++ b/python/0.992.0/text/index.html @@ -0,0 +1,1557 @@ + + + + + + + + + + + + + + + + + + + + + + + + Human-readable text syntax - Python Preserves + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + +

Human-readable text syntax

+ + +
+ + + +
+ +

The preserves.text module implements the Preserves human-readable text +syntax.

+

The main entry points are functions stringify, +parse, and +parse_with_annotations.

+
>>> stringify(Record(Symbol('hi'), [1, [2, 3]]))
+'<hi 1 [2 3]>'
+>>> parse('<hi 1 [2 3]>')
+#hi(1, (2, 3))
+
+ + + +
+ + + + + + + + +
+ + + +

+Formatter(format_embedded=lambda x: x, indent=None, with_commas=False, trailing_comma=False, include_annotations=True) + +

+ + +
+

+ Bases: TextCodec

+ + +

Printer (and indenting pretty-printer) for producing human-readable syntax from +Preserves Values.

+
>>> f = Formatter()
+>>> f.append({'a': 1, 'b': 2})
+>>> f.append(Record(Symbol('label'), ['field1', ['field2item1', 'field2item2']]))
+>>> print(f.contents())
+{"a": 1 "b": 2} <label "field1" ["field2item1" "field2item2"]>
+
+>>> f = Formatter(indent=4)
+>>> f.append({'a': 1, 'b': 2})
+>>> f.append(Record(Symbol('label'), ['field1', ['field2item1', 'field2item2']]))
+>>> print(f.contents())
+{
+    "a": 1
+    "b": 2
+}
+<label "field1" [
+    "field2item1"
+    "field2item2"
+]>
+
+ +

Parameters:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescriptionDefault
format_embedded +

function accepting an Embedded.embeddedValue and +returning a Value for serialization.

+ lambda x: x +
indent + int | None +

None disables indented pretty-printing; otherwise, an int specifies indentation +per nesting-level.

+ None +
with_commas + bool +

True causes commas to separate sequence and set items and dictionary entries; +False omits commas.

+ False +
trailing_comma + bool +

True causes a comma to be printed after the final item or entry in a sequence, +set or dictionary; False omits this trailing comma

+ False +
include_annotations + bool +

True causes annotations to be included in the output; False causes them to be +omitted.

+ True +
+ +

Attributes:

+ + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
indent_delta + int +

indentation per nesting-level

chunks + list[str] +

fragments of output

+ + +
+ Source code in preserves/text.py +
472
+473
+474
+475
+476
+477
+478
+479
+480
+481
+482
+483
+484
+485
+486
def __init__(self,
+             format_embedded=lambda x: x,
+             indent=None,
+             with_commas=False,
+             trailing_comma=False,
+             include_annotations=True):
+    super(Formatter, self).__init__()
+    self.indent_delta = 0 if indent is None else indent
+    self.indent_distance = 0
+    self.nesting = 0
+    self.with_commas = with_commas
+    self.trailing_comma = trailing_comma
+    self.chunks = []
+    self._format_embedded = format_embedded
+    self.include_annotations = include_annotations
+
+
+ + + +
+ + + + + + + + + +
+ + + +

+append(v) + +

+ + +
+ +

Extend self.chunks with at least one chunk, together making up the text +representation of v.

+ +
+ Source code in preserves/text.py +
542
+543
+544
+545
+546
+547
+548
+549
+550
+551
def append(self, v):
+    """Extend `self.chunks` with at least one chunk, together making up the text
+    representation of `v`."""
+    if self.chunks and self.nesting == 0:
+        self.write_indent_space()
+    try:
+        self.nesting += 1
+        self._append(v)
+    finally:
+        self.nesting -= 1
+
+
+
+ +
+ +
+ + + +

+contents() + +

+ + +
+ +

Returns a str constructed from the join of the chunks in self.chunks.

+ +
+ Source code in preserves/text.py +
493
+494
+495
def contents(self):
+    """Returns a `str` constructed from the join of the chunks in `self.chunks`."""
+    return u''.join(self.chunks)
+
+
+
+ +
+ +
+ + + +

+is_indenting() + +

+ + +
+ +

Returns True iff this Formatter is in pretty-printing +indenting mode.

+ +
+ Source code in preserves/text.py +
497
+498
+499
+500
def is_indenting(self):
+    """Returns `True` iff this [Formatter][preserves.text.Formatter] is in pretty-printing
+    indenting mode."""
+    return self.indent_delta > 0
+
+
+
+ +
+ + + +
+ +
+ +
+ +
+ + + +

+Parser(input_buffer='', include_annotations=False, parse_embedded=lambda x: x) + +

+ + +
+

+ Bases: TextCodec

+ + +

Parser for the human-readable Preserves text syntax.

+ +

Parameters:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescriptionDefault
input_buffer + str +

initial contents of the input buffer; may subsequently be extended by calling +extend.

+ '' +
include_annotations + bool +

if True, wrap each value and subvalue in an +Annotated object.

+ False +
parse_embedded +

function accepting a Value and returning a possibly-decoded form of that value +suitable for placing into an Embedded object.

+ lambda x: x +
+

Normal usage is to supply input text, and keep calling next +until a ShortPacket exception is raised:

+
>>> d = Parser('123 "hello" @x []')
+>>> d.next()
+123
+>>> d.next()
+'hello'
+>>> d.next()
+()
+>>> d.next()
+Traceback (most recent call last):
+  ...
+preserves.error.ShortPacket: Short input buffer
+
+

Alternatively, keep calling try_next until it yields +None, which is not in the domain of Preserves Values:

+
>>> d = Parser('123 "hello" @x []')
+>>> d.try_next()
+123
+>>> d.try_next()
+'hello'
+>>> d.try_next()
+()
+>>> d.try_next()
+
+

For convenience, Parser implements the iterator interface, +backing it with try_next, so you can simply iterate +over all complete values in an input:

+
>>> d = Parser('123 "hello" @x []')
+>>> list(d)
+[123, 'hello', ()]
+
+
>>> for v in Parser('123 "hello" @x []'):
+...     print(repr(v))
+123
+'hello'
+()
+
+

Supply include_annotations=True to read annotations alongside the annotated values:

+
>>> d = Parser('123 "hello" @x []', include_annotations=True)
+>>> list(d)
+[123, 'hello', @#x ()]
+
+

If you are incrementally reading from, say, a socket, you can use +extend to add new input as if comes available:

+
>>> d = Parser('123 "he')
+>>> d.try_next()
+123
+>>> d.try_next() # returns None because the input is incomplete
+>>> d.extend('llo"')
+>>> d.try_next()
+'hello'
+>>> d.try_next()
+
+ +

Attributes:

+ + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
input_buffer + str +

buffered input waiting to be processed

index + int +

read position within input_buffer

+ + +
+ Source code in preserves/text.py +
132
+133
+134
+135
+136
+137
def __init__(self, input_buffer=u'', include_annotations=False, parse_embedded=lambda x: x):
+    super(Parser, self).__init__()
+    self.input_buffer = input_buffer
+    self.index = 0
+    self.include_annotations = include_annotations
+    self.parse_embedded = parse_embedded
+
+
+ + + +
+ + + + + + + + + +
+ + + +

+extend(text) + +

+ + +
+ +

Appends text to the remaining contents of self.input_buffer, trimming already-processed +text from the front of self.input_buffer and resetting self.index to zero.

+ +
+ Source code in preserves/text.py +
139
+140
+141
+142
+143
def extend(self, text):
+    """Appends `text` to the remaining contents of `self.input_buffer`, trimming already-processed
+    text from the front of `self.input_buffer` and resetting `self.index` to zero."""
+    self.input_buffer = self.input_buffer[self.index:] + text
+    self.index = 0
+
+
+
+ +
+ +
+ + + +

+next() + +

+ + +
+ +

Reads the next complete Value from the internal buffer, raising +ShortPacket if too few bytes are available, or +DecodeError if the input is invalid somehow.

+ +
+ Source code in preserves/text.py +
327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
def next(self):
+    """Reads the next complete `Value` from the internal buffer, raising
+    [ShortPacket][preserves.error.ShortPacket] if too few bytes are available, or
+    [DecodeError][preserves.error.DecodeError] if the input is invalid somehow.
+
+    """
+    self.skip_whitespace()
+    c = self.peek()
+    if c == '"':
+        self.skip()
+        return self.wrap(self.read_string('"'))
+    if c == '|':
+        self.skip()
+        return self.wrap(Symbol(self.read_string('|')))
+    if c == '@':
+        self.skip()
+        return self.unshift_annotation(self.next(), self.next())
+    if c == ';':
+        raise DecodeError('Semicolon is reserved syntax')
+    if c == ':':
+        raise DecodeError('Unexpected key/value separator between items')
+    if c == '#':
+        self.skip()
+        c = self.nextchar()
+        if c in ' \t': return self.unshift_annotation(self.comment_line(), self.next())
+        if c in '\n\r': return self.unshift_annotation('', self.next())
+        if c == 'f': self.require_delimiter('#f'); return self.wrap(False)
+        if c == 't': self.require_delimiter('#t'); return self.wrap(True)
+        if c == '{': return self.wrap(self.read_set())
+        if c == '"': return self.wrap(self.read_literal_binary())
+        if c == 'x':
+            c = self.nextchar()
+            if c == '"': return self.wrap(self.read_hex_binary())
+            if c == 'f': return self.wrap(self.read_hex_float(4))
+            if c == 'd': return self.wrap(self.read_hex_float(8))
+            raise DecodeError('Invalid #x syntax')
+        if c == '[': return self.wrap(self.read_base64_binary())
+        if c == '!':
+            if self.parse_embedded is None:
+                raise DecodeError('No parse_embedded function supplied')
+            return self.wrap(Embedded(self.parse_embedded(self.next())))
+        raise DecodeError('Invalid # syntax')
+    if c == '<':
+        self.skip()
+        vs = self.upto('>', False)
+        if len(vs) == 0:
+            raise DecodeError('Missing record label')
+        return self.wrap(Record(vs[0], vs[1:]))
+    if c == '[':
+        self.skip()
+        return self.wrap(self.upto(']', True))
+    if c == '{':
+        self.skip()
+        return self.wrap(self.read_dictionary())
+    if c in '>]},':
+        raise DecodeError('Unexpected ' + c)
+    self.skip()
+    return self.wrap(self.read_raw_symbol_or_number([c]))
+
+
+
+ +
+ +
+ + + +

+try_next() + +

+ + +
+ +

Like next, but returns None instead of raising +ShortPacket.

+ +
+ Source code in preserves/text.py +
386
+387
+388
+389
+390
+391
+392
+393
+394
def try_next(self):
+    """Like [next][preserves.text.Parser.next], but returns `None` instead of raising
+    [ShortPacket][preserves.error.ShortPacket]."""
+    start = self.index
+    try:
+        return self.next()
+    except ShortPacket:
+        self.index = start
+        return None
+
+
+
+ +
+ + + +
+ +
+ +
+ + +
+ + + +

+parse(text, **kwargs) + +

+ + +
+ +

Yields the first complete encoded value from text, passing kwargs through to the +Parser constructor. Raises exceptions as per +next.

+ +

Parameters:

+ + + + + + + + + + + + + + + + + +
NameTypeDescriptionDefault
text + str +

encoded data to decode

+ required +
+ +
+ Source code in preserves/text.py +
405
+406
+407
+408
+409
+410
+411
+412
+413
+414
def parse(text, **kwargs):
+    """Yields the first complete encoded value from `text`, passing `kwargs` through to the
+    [Parser][preserves.text.Parser] constructor. Raises exceptions as per
+    [next][preserves.text.Parser.next].
+
+    Args:
+        text (str): encoded data to decode
+
+    """
+    return Parser(input_buffer=text, **kwargs).next()
+
+
+
+ +
+ +
+ + + +

+parse_with_annotations(bs, **kwargs) + +

+ + +
+ +

Like parse, but supplying include_annotations=True to the +Parser constructor.

+ +
+ Source code in preserves/text.py +
416
+417
+418
+419
def parse_with_annotations(bs, **kwargs):
+    """Like [parse][preserves.text.parse], but supplying `include_annotations=True` to the
+    [Parser][preserves.text.Parser] constructor."""
+    return Parser(input_buffer=bs, include_annotations=True, **kwargs).next()
+
+
+
+ +
+ +
+ + + +

+stringify(v, **kwargs) + +

+ + +
+ +

Convert a single Value v to a string. Any supplied kwargs are passed on to the +underlying Formatter constructor.

+ +
+ Source code in preserves/text.py +
603
+604
+605
+606
+607
+608
def stringify(v, **kwargs):
+    """Convert a single `Value` `v` to a string. Any supplied `kwargs` are passed on to the
+    underlying [Formatter][preserves.text.Formatter] constructor."""
+    e = Formatter(**kwargs)
+    e.append(v)
+    return e.contents()
+
+
+
+ +
+ + + +
+ +
+ +
+ +
+
+ + + Last update: + March 16, 2023 + +
+ Created: + March 16, 2023 + + +
+
+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/python/0.992.0/values/index.html b/python/0.992.0/values/index.html new file mode 100644 index 0000000..8a157a8 --- /dev/null +++ b/python/0.992.0/values/index.html @@ -0,0 +1,2555 @@ + + + + + + + + + + + + + + + + + + + + + + Representations of Values - Python Preserves + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ + + + + + + + +
+ + +
+ +
+ + + + + + +
+
+ + + +
+
+
+ + + + +
+
+
+ + + +
+
+
+ + + +
+
+
+ + + +
+
+ + + + + + + +

Representations of Values

+

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.

+

Python's lists and tuples correspond to Preserves Sequences, and dicts and sets to +Dictionary and Set values, respectively. Preserves Records are represented by +Record objects. Finally, embedded values are represented by +Embedded objects.

+ + +
+ + + +
+ +

The preserves.values module implements the core representations of Preserves +Values as Python values.

+ + + +
+ + + + + + + + +
+ + + +

+Annotated(item) + +

+ + +
+

+ Bases: object

+ + +

A Preserves Value along with a sequence of Values annotating it. Compares equal to +the underlying Value, ignoring the annotations. See the specification document for more +about annotations.

+
>>> import preserves
+>>> a = preserves.parse('''
+... # A comment
+... [1 2 3]
+... ''', include_annotations=True)
+>>> a
+@'A comment' (1, 2, 3)
+>>> a.item
+(1, 2, 3)
+>>> a.annotations
+['A comment']
+>>> a == (1, 2, 3)
+True
+>>> a == preserves.parse('@xyz [1 2 3]', include_annotations=True)
+True
+>>> a[0]
+Traceback (most recent call last):
+  ...
+TypeError: 'Annotated' object is not subscriptable
+>>> a.item[0]
+1
+>>> type(a.item[0])
+<class 'preserves.values.Annotated'>
+>>> a.item[0].annotations
+[]
+>>> print(preserves.stringify(a))
+@"A comment" [1 2 3]
+>>> print(preserves.stringify(a, include_annotations=False))
+[1 2 3]
+
+ +

Attributes:

+ + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
item + Value +

the underlying annotated Value

annotations + list[Value] +

the annotations attached to self.item

+ + +
+ Source code in preserves/values.py +
578
+579
+580
def __init__(self, item):
+    self.annotations = []
+    self.item = item
+
+
+ + + +
+ + + + + + + + + +
+ + + +

+peel() + +

+ + +
+ +

Calls strip_annotations on self with depth=1.

+ +
+ Source code in preserves/values.py +
601
+602
+603
def peel(self):
+    """Calls [strip_annotations][preserves.values.strip_annotations] on `self` with `depth=1`."""
+    return strip_annotations(self, 1)
+
+
+
+ +
+ +
+ + + +

+strip(depth=inf) + +

+ + +
+ +

Calls strip_annotations on self and depth.

+ +
+ Source code in preserves/values.py +
597
+598
+599
def strip(self, depth=inf):
+    """Calls [strip_annotations][preserves.values.strip_annotations] on `self` and `depth`."""
+    return strip_annotations(self, depth)
+
+
+
+ +
+ + + +
+ +
+ +
+ +
+ + + +

+Embedded(embeddedValue) + +

+ + +
+ + +

Representation of a Preserves Embedded value. For more on the meaning and use of +embedded values, see the specification.

+
>>> import io
+>>> e = Embedded(io.StringIO('some text'))
+>>> e                                        # doctest: +ELLIPSIS
+#!<_io.StringIO object at ...>
+>>> e.embeddedValue                          # doctest: +ELLIPSIS
+<_io.StringIO object at ...>
+
+
>>> import preserves
+>>> print(preserves.stringify(Embedded(None)))
+Traceback (most recent call last):
+  ...
+TypeError: Cannot preserves-format: None
+>>> print(preserves.stringify(Embedded(None), format_embedded=lambda x: 'abcdef'))
+#!"abcdef"
+
+ +

Attributes:

+ + + + + + + + + + + + + + + +
NameTypeDescription
embeddedValue +

any Python value; could be a platform object, could be a representation of a +Preserves Value, could be None, could be anything!

+ + +
+ Source code in preserves/values.py +
723
+724
def __init__(self, embeddedValue):
+    self.embeddedValue = embeddedValue
+
+
+ + + +
+ + + + + + + + + + + +
+ +
+ +
+ +
+ + + +

+Float(value) + +

+ + +
+

+ Bases: object

+ + +

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.)

+
>>> Float(3.45)
+Float(3.45)
+>>> import preserves
+>>> preserves.stringify(Float(3.45))
+'3.45f'
+>>> preserves.stringify(3.45)
+'3.45'
+>>> preserves.parse('3.45f')
+Float(3.45)
+>>> preserves.parse('3.45')
+3.45
+>>> preserves.encode(Float(3.45))
+b'\x87\x04@\\\xcc\xcd'
+>>> preserves.encode(3.45)
+b'\x87\x08@\x0b\x99\x99\x99\x99\x99\x9a'
+
+ +

Attributes:

+ + + + + + + + + + + + + + + +
NameTypeDescription
value + float +

the double-precision representation of intended single-precision value

+ + +
+ Source code in preserves/values.py +
69
+70
def __init__(self, value):
+    self.value = value
+
+
+ + + +
+ + + + + + + + + +
+ + + +

+from_bytes(bs) + + + staticmethod + + +

+ + +
+ +

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 struct.unpack('>f', ...) +equivalent.

+
>>> Float.from_bytes(b'\x7f\x80\x00{')
+Float(nan)
+>>> Float.from_bytes(b'\x7f\x80\x00{').to_bytes()
+b'\x7f\x80\x00{'
+
+>>> struct.unpack('>f', b'\x7f\x80\x00{')[0]
+nan
+>>> Float(struct.unpack('>f', b'\x7f\x80\x00{')[0]).to_bytes()
+b'\x7f\xc0\x00{'
+>>> struct.pack('>f', struct.unpack('>f', b'\x7f\x80\x00{')[0])
+b'\x7f\xc0\x00{'
+
+

(Note well the difference between 7f80007b and 7fc0007b!)

+ +
+ Source code in preserves/values.py +
136
+137
+138
+139
+140
+141
+142
+143
+144
+145
+146
+147
+148
+149
+150
+151
+152
+153
+154
+155
+156
+157
+158
+159
+160
+161
+162
+163
+164
+165
+166
+167
+168
+169
@staticmethod
+def from_bytes(bs):
+    """Converts a 4-byte-long byte string to a 32-bit single-precision floating point value
+    wrapped in a [Float][preserves.values.Float] instance. Takes care to preserve the
+    quiet/signalling bit-pattern of NaN values, unlike its `struct.unpack('>f', ...)`
+    equivalent.
+
+    ```python
+    >>> Float.from_bytes(b'\\x7f\\x80\\x00{')
+    Float(nan)
+    >>> Float.from_bytes(b'\\x7f\\x80\\x00{').to_bytes()
+    b'\\x7f\\x80\\x00{'
+
+    >>> struct.unpack('>f', b'\\x7f\\x80\\x00{')[0]
+    nan
+    >>> Float(struct.unpack('>f', b'\\x7f\\x80\\x00{')[0]).to_bytes()
+    b'\\x7f\\xc0\\x00{'
+    >>> struct.pack('>f', struct.unpack('>f', b'\\x7f\\x80\\x00{')[0])
+    b'\\x7f\\xc0\\x00{'
+
+    ```
+
+    (Note well the difference between `7f80007b` and `7fc0007b`!)
+
+    """
+    vf = struct.unpack('>I', bs)[0]
+    if (vf & 0x7f800000) == 0x7f800000:
+        # NaN or inf. Preserve quiet/signalling bit by manually expanding to double-precision.
+        sign = vf >> 31
+        payload = vf & 0x007fffff
+        dbs = struct.pack('>Q', (sign << 63) | 0x7ff0000000000000 | (payload << 29))
+        return Float(struct.unpack('>d', dbs)[0])
+    else:
+        return Float(struct.unpack('>f', bs)[0])
+
+
+
+ +
+ +
+ + + +

+to_bytes() + +

+ + +
+ +

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 +struct.pack('>f', ...) equivalent.

+
>>> Float.from_bytes(b'\x7f\x80\x00{')
+Float(nan)
+>>> Float.from_bytes(b'\x7f\x80\x00{').to_bytes()
+b'\x7f\x80\x00{'
+
+>>> struct.unpack('>f', b'\x7f\x80\x00{')[0]
+nan
+>>> Float(struct.unpack('>f', b'\x7f\x80\x00{')[0]).to_bytes()
+b'\x7f\xc0\x00{'
+>>> struct.pack('>f', struct.unpack('>f', b'\x7f\x80\x00{')[0])
+b'\x7f\xc0\x00{'
+
+

(Note well the difference between 7f80007b and 7fc0007b!)

+ +
+ Source code in preserves/values.py +
 91
+ 92
+ 93
+ 94
+ 95
+ 96
+ 97
+ 98
+ 99
+100
+101
+102
+103
+104
+105
+106
+107
+108
+109
+110
+111
+112
+113
+114
+115
+116
+117
+118
+119
+120
+121
+122
+123
def to_bytes(self):
+    """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
+    `struct.pack('>f', ...)` equivalent.
+
+    ```python
+    >>> Float.from_bytes(b'\\x7f\\x80\\x00{')
+    Float(nan)
+    >>> Float.from_bytes(b'\\x7f\\x80\\x00{').to_bytes()
+    b'\\x7f\\x80\\x00{'
+
+    >>> struct.unpack('>f', b'\\x7f\\x80\\x00{')[0]
+    nan
+    >>> Float(struct.unpack('>f', b'\\x7f\\x80\\x00{')[0]).to_bytes()
+    b'\\x7f\\xc0\\x00{'
+    >>> struct.pack('>f', struct.unpack('>f', b'\\x7f\\x80\\x00{')[0])
+    b'\\x7f\\xc0\\x00{'
+
+    ```
+
+    (Note well the difference between `7f80007b` and `7fc0007b`!)
+
+    """
+
+    if math.isnan(self.value) or math.isinf(self.value):
+        dbs = struct.pack('>d', self.value)
+        vd = struct.unpack('>Q', dbs)[0]
+        sign = vd >> 63
+        payload = (vd >> 29) & 0x007fffff
+        vf = (sign << 31) | 0x7f800000 | payload
+        return struct.pack('>I', vf)
+    else:
+        return struct.pack('>f', self.value)
+
+
+
+ +
+ + + +
+ +
+ +
+ +
+ + + +

+ImmutableDict(*args, **kwargs) + +

+ + +
+

+ Bases: dict

+ + +

A subclass of Python's built-in dict that overrides methods that could mutate the +dictionary, causing them to raise TypeError('Immutable') if called.

+

Implements the __hash__ method, allowing ImmutableDict +instances to be used whereever immutable data are permitted; in particular, as keys in +other dictionaries.

+
>>> d = ImmutableDict([('a', 1), ('b', 2)])
+>>> d
+{'a': 1, 'b': 2}
+>>> d['c'] = 3
+Traceback (most recent call last):
+  ...
+TypeError: Immutable
+>>> del d['b']
+Traceback (most recent call last):
+  ...
+TypeError: Immutable
+
+ + +
+ Source code in preserves/values.py +
462
+463
+464
+465
def __init__(self, *args, **kwargs):
+    if hasattr(self, '__hash'): raise TypeError('Immutable')
+    super(ImmutableDict, self).__init__(*args, **kwargs)
+    self.__hash = None
+
+
+ + + +
+ + + + + + + + + +
+ + + +

+from_kvs(kvs) + + + staticmethod + + +

+ + +
+ +

Constructs an ImmutableDict from a sequence of +alternating keys and values; compare to the +ImmutableDict constructor, which takes a sequence of +key-value pairs.

+
>>> ImmutableDict.from_kvs(['a', 1, 'b', 2])
+{'a': 1, 'b': 2}
+>>> ImmutableDict.from_kvs(['a', 1, 'b', 2])['c'] = 3
+Traceback (most recent call last):
+  ...
+TypeError: Immutable
+
+ +
+ Source code in preserves/values.py +
483
+484
+485
+486
+487
+488
+489
+490
+491
+492
+493
+494
+495
+496
+497
+498
+499
+500
+501
+502
+503
+504
+505
+506
+507
+508
+509
+510
+511
+512
+513
+514
+515
+516
+517
@staticmethod
+def from_kvs(kvs):
+    """Constructs an [ImmutableDict][preserves.values.ImmutableDict] from a sequence of
+    alternating keys and values; compare to the
+    [ImmutableDict][preserves.values.ImmutableDict] constructor, which takes a sequence of
+    key-value pairs.
+
+    ```python
+    >>> ImmutableDict.from_kvs(['a', 1, 'b', 2])
+    {'a': 1, 'b': 2}
+    >>> ImmutableDict.from_kvs(['a', 1, 'b', 2])['c'] = 3
+    Traceback (most recent call last):
+      ...
+    TypeError: Immutable
+
+    ```
+
+    """
+
+    i = iter(kvs)
+    result = ImmutableDict()
+    result_proxy = super(ImmutableDict, result)
+    try:
+        while True:
+            k = next(i)
+            try:
+                v = next(i)
+            except StopIteration:
+                raise DecodeError("Missing dictionary value")
+            if k in result:
+                raise DecodeError("Duplicate key: " + repr(k))
+            result_proxy.__setitem__(k, v)
+    except StopIteration:
+        pass
+    return result
+
+
+
+ +
+ + + +
+ +
+ +
+ +
+ + + +

+Record(key, fields) + +

+ + +
+

+ Bases: object

+ + +

Representation of Preserves Records, which are a pair of a label Value and a sequence of field Values.

+
>>> r = Record(Symbol('label'), ['field1', ['field2item1', 'field2item2']])
+>>> r
+#label('field1', ['field2item1', 'field2item2'])
+>>> r.key
+#label
+>>> r.fields
+('field1', ['field2item1', 'field2item2'])
+>>> import preserves
+>>> preserves.stringify(r)
+'<label "field1" ["field2item1" "field2item2"]>'
+>>> r == preserves.parse('<label "field1" ["field2item1" "field2item2"]>')
+True
+
+ +

Parameters:

+ + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescriptionDefault
key + Value +

the Record's label

+ required +
fields + iterable[Value] +

the fields of the Record

+ required +
+ +

Attributes:

+ + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
key + Value +

the Record's label

fields + tuple[Value] +

the fields of the Record

+ + +
+ Source code in preserves/values.py +
274
+275
+276
+277
def __init__(self, key, fields):
+    self.key = key
+    self.fields = tuple(fields)
+    self.__hash = None
+
+
+ + + +
+ + + + + + + + + +
+ + + +

+makeBasicConstructor(label, fieldNames) + + + staticmethod + + +

+ + +
+ +

Constructs and returns a "constructor" for Records having a certain label and +number of fields.

+ +
+ Deprecated +

Use preserves.schema definitions instead.

+

The "constructor" is a callable function that accepts len(fields) arguments and +returns a Record with label as its label and the arguments +to the constructor as field values.

+

In addition, the "constructor" has a constructorInfo attribute holding a +RecordConstructorInfo object, an isClassOf +attribute holding a unary function that returns True iff its argument is a +Record with label label and arity len(fieldNames), and +an ensureClassOf attribute that raises an Exception if isClassOf returns false on +its argument and returns the argument otherwise.

+

Finally, for each field name f in fieldNames, the "constructor" object has an +attribute _f that is a unary function that retrieves the f field from the passed in +argument.

+
>>> c = Record.makeBasicConstructor(Symbol('date'), 'year month day')
+>>> c(1969, 7, 16)
+#date(1969, 7, 16)
+>>> c.constructorInfo
+#date/3
+>>> c.isClassOf(c(1969, 7, 16))
+True
+>>> c.isClassOf(Record(Symbol('date'), [1969, 7, 16]))
+True
+>>> c.isClassOf(Record(Symbol('date'), [1969]))
+False
+>>> c.ensureClassOf(c(1969, 7, 16))
+#date(1969, 7, 16)
+>>> c.ensureClassOf(Record(Symbol('date'), [1969]))
+Traceback (most recent call last):
+  ...
+TypeError: Record: expected #date/3, got #date(1969)
+>>> c._year(c(1969, 7, 16))
+1969
+>>> c._month(c(1969, 7, 16))
+7
+>>> c._day(c(1969, 7, 16))
+16
+
+ +

Parameters:

+ + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescriptionDefault
label + Value +

Label to use for constructed/matched Records

+ required +
fieldNames + tuple[str] | list[str] | str +

Names of the Record's fields

+ required +
+ +
+ Source code in preserves/values.py +
322
+323
+324
+325
+326
+327
+328
+329
+330
+331
+332
+333
+334
+335
+336
+337
+338
+339
+340
+341
+342
+343
+344
+345
+346
+347
+348
+349
+350
+351
+352
+353
+354
+355
+356
+357
+358
+359
+360
+361
+362
+363
+364
+365
+366
+367
+368
+369
+370
+371
+372
+373
+374
+375
+376
+377
+378
+379
+380
+381
+382
+383
+384
+385
+386
+387
+388
+389
+390
+391
+392
+393
+394
+395
+396
+397
+398
+399
+400
+401
@staticmethod
+def makeBasicConstructor(label, fieldNames):
+    """Constructs and returns a "constructor" for `Record`s having a certain `label` and
+    number of fields.
+
+    Deprecated:
+       Use [preserves.schema][] definitions instead.
+
+    The "constructor" is a callable function that accepts `len(fields)` arguments and
+    returns a [Record][preserves.values.Record] with `label` as its label and the arguments
+    to the constructor as field values.
+
+    In addition, the "constructor" has a `constructorInfo` attribute holding a
+    [RecordConstructorInfo][preserves.values.RecordConstructorInfo] object, an `isClassOf`
+    attribute holding a unary function that returns `True` iff its argument is a
+    [Record][preserves.values.Record] with label `label` and arity `len(fieldNames)`, and
+    an `ensureClassOf` attribute that raises an `Exception` if `isClassOf` returns false on
+    its argument and returns the argument otherwise.
+
+    Finally, for each field name `f` in `fieldNames`, the "constructor" object has an
+    attribute `_f` that is a unary function that retrieves the `f` field from the passed in
+    argument.
+
+    ```python
+    >>> c = Record.makeBasicConstructor(Symbol('date'), 'year month day')
+    >>> c(1969, 7, 16)
+    #date(1969, 7, 16)
+    >>> c.constructorInfo
+    #date/3
+    >>> c.isClassOf(c(1969, 7, 16))
+    True
+    >>> c.isClassOf(Record(Symbol('date'), [1969, 7, 16]))
+    True
+    >>> c.isClassOf(Record(Symbol('date'), [1969]))
+    False
+    >>> c.ensureClassOf(c(1969, 7, 16))
+    #date(1969, 7, 16)
+    >>> c.ensureClassOf(Record(Symbol('date'), [1969]))
+    Traceback (most recent call last):
+      ...
+    TypeError: Record: expected #date/3, got #date(1969)
+    >>> c._year(c(1969, 7, 16))
+    1969
+    >>> c._month(c(1969, 7, 16))
+    7
+    >>> c._day(c(1969, 7, 16))
+    16
+
+    ```
+
+    Args:
+        label (Value): Label to use for constructed/matched `Record`s
+        fieldNames (tuple[str] | list[str] | str): Names of the `Record`'s fields
+
+    """
+    if type(fieldNames) == str:
+        fieldNames = fieldNames.split()
+    arity = len(fieldNames)
+    def ctor(*fields):
+        if len(fields) != arity:
+            raise Exception("Record: cannot instantiate %r expecting %d fields with %d fields"%(
+                label,
+                arity,
+                len(fields)))
+        return Record(label, fields)
+    ctor.constructorInfo = RecordConstructorInfo(label, arity)
+    ctor.isClassOf = lambda v: \
+                     isinstance(v, Record) and v.key == label and len(v.fields) == arity
+    def ensureClassOf(v):
+        if not ctor.isClassOf(v):
+            raise TypeError("Record: expected %r/%d, got %r" % (label, arity, v))
+        return v
+    ctor.ensureClassOf = ensureClassOf
+    for fieldIndex in range(len(fieldNames)):
+        fieldName = fieldNames[fieldIndex]
+        # Stupid python scoping bites again
+        def getter(fieldIndex):
+            return lambda v: ensureClassOf(v)[fieldIndex]
+        setattr(ctor, '_' + fieldName, getter(fieldIndex))
+    return ctor
+
+
+
+ +
+ +
+ + + +

+makeConstructor(labelSymbolText, fieldNames) + + + staticmethod + + +

+ + +
+ +

Equivalent to Record.makeBasicConstructor(Symbol(labelSymbolText), fieldNames).

+ +
+ Deprecated +

Use preserves.schema definitions instead.

+
+
+ Source code in preserves/values.py +
312
+313
+314
+315
+316
+317
+318
+319
+320
@staticmethod
+def makeConstructor(labelSymbolText, fieldNames):
+    """
+    Equivalent to `Record.makeBasicConstructor(Symbol(labelSymbolText), fieldNames)`.
+
+    Deprecated:
+       Use [preserves.schema][] definitions instead.
+    """
+    return Record.makeBasicConstructor(Symbol(labelSymbolText), fieldNames)
+
+
+
+ +
+ + + +
+ +
+ +
+ +
+ + + +

+RecordConstructorInfo(key, arity) + +

+ + +
+

+ Bases: object

+ + +

Describes the shape of a Record constructor, namely its label and its arity (field +count).

+
>>> RecordConstructorInfo(Symbol('label'), 3)
+#label/3
+
+ +

Attributes:

+ + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
key + Value +

the label of matching Records

arity + int +

the number of fields in matching Records

+ + +
+ Source code in preserves/values.py +
417
+418
+419
def __init__(self, key, arity):
+    self.key = key
+    self.arity = arity
+
+
+ + + +
+ + + + + + + + + + + +
+ +
+ +
+ +
+ + + +

+Symbol(name) + +

+ + +
+

+ Bases: object

+ + +

Representation of Preserves Symbols.

+
>>> Symbol('xyz')
+#xyz
+>>> Symbol('xyz').name
+'xyz'
+>>> import preserves
+>>> preserves.stringify(Symbol('xyz'))
+'xyz'
+>>> preserves.stringify(Symbol('hello world'))
+'|hello world|'
+>>> preserves.parse('xyz')
+#xyz
+>>> preserves.parse('|hello world|')
+#hello world
+
+ +

Attributes:

+ + + + + + + + + + + + + + + +
NameTypeDescription
name + str | Symbol +

The symbol's text label. If an existing Symbol is passed +in, the existing Symbol's name is used as the name for the new Symbol.

+ + +
+ Source code in preserves/values.py +
203
+204
def __init__(self, name):
+    self.name = name.name if isinstance(name, Symbol) else name
+
+
+ + + +
+ + + + + + + + + + + +
+ +
+ +
+ + +
+ + + +

+annotate(v, *anns) + +

+ + +
+ +

Wraps v in an Annotated object, if it isn't already +wrapped, and appends each of the anns to the Annotated's +annotations sequence. NOTE: Does not recursively ensure that any parts of the argument +v are themselves wrapped in Annotated objects!

+
>>> import preserves
+>>> print(preserves.stringify(annotate(123, "A comment", "Another comment")))
+@"A comment" @"Another comment" 123
+
+ +
+ Source code in preserves/values.py +
667
+668
+669
+670
+671
+672
+673
+674
+675
+676
+677
+678
+679
+680
+681
+682
+683
+684
def annotate(v, *anns):
+    """Wraps `v` in an [Annotated][preserves.values.Annotated] object, if it isn't already
+    wrapped, and appends each of the `anns` to the [Annotated][preserves.values.Annotated]'s
+    `annotations` sequence. NOTE: Does not recursively ensure that any parts of the argument
+    `v` are themselves wrapped in [Annotated][preserves.values.Annotated] objects!
+
+    ```python
+    >>> import preserves
+    >>> print(preserves.stringify(annotate(123, "A comment", "Another comment")))
+    @"A comment" @"Another comment" 123
+
+    ```
+    """
+    if not is_annotated(v):
+        v = Annotated(v)
+    for a in anns:
+        v.annotations.append(a)
+    return v
+
+
+
+ +
+ +
+ + + +

+cmp_floats(a, b) + +

+ + +
+ +

Implements the totalOrder predicate defined in section 5.10 of IEEE Std +754-2008.

+ +
+ Source code in preserves/values.py +
31
+32
+33
+34
+35
+36
+37
+38
+39
+40
def cmp_floats(a, b):
+    """Implements the `totalOrder` predicate defined in section 5.10 of [IEEE Std
+    754-2008](https://dx.doi.org/10.1109/IEEESTD.2008.4610935).
+
+    """
+    a = float_to_int(a)
+    b = float_to_int(b)
+    if a & 0x8000000000000000: a = a ^ 0x7fffffffffffffff
+    if b & 0x8000000000000000: b = b ^ 0x7fffffffffffffff
+    return a - b
+
+
+
+ +
+ +
+ + + +

+dict_kvs(d) + +

+ + +
+ +

Generator function yielding a sequence of alternating keys and values from d. In some +sense the inverse of ImmutableDict.from_kvs.

+
>>> list(dict_kvs({'a': 1, 'b': 2}))
+['a', 1, 'b', 2]
+
+ +
+ Source code in preserves/values.py +
519
+520
+521
+522
+523
+524
+525
+526
+527
+528
+529
+530
+531
def dict_kvs(d):
+    """Generator function yielding a sequence of alternating keys and values from `d`. In some
+    sense the inverse of [ImmutableDict.from_kvs][preserves.values.ImmutableDict.from_kvs].
+
+    ```python
+    >>> list(dict_kvs({'a': 1, 'b': 2}))
+    ['a', 1, 'b', 2]
+
+    ```
+    """
+    for k in d:
+        yield k
+        yield d[k]
+
+
+
+ +
+ +
+ + + +

+is_annotated(v) + +

+ + +
+ +

True iff v is an instance of Annotated.

+ +
+ Source code in preserves/values.py +
617
+618
+619
def is_annotated(v):
+    """`True` iff `v` is an instance of [Annotated][preserves.values.Annotated]."""
+    return isinstance(v, Annotated)
+
+
+
+ +
+ +
+ + + +

+preserve(v) + +

+ + +
+ +

Converts v to a representation of a Preserves Value by (repeatedly) setting

+
v = v.__preserve__()
+
+

while v has a __preserve__ method. Parsed Schema +values are able to render themselves to their serialized representations this way.

+ +
+ Source code in preserves/values.py +
13
+14
+15
+16
+17
+18
+19
+20
+21
+22
+23
+24
+25
+26
def preserve(v):
+    """Converts `v` to a representation of a Preserves `Value` by (repeatedly) setting
+
+    ```python
+    v = v.__preserve__()
+    ```
+
+    while `v` has a `__preserve__` method. Parsed [Schema][preserves.schema]
+    values are able to render themselves to their serialized representations this way.
+
+    """
+    while hasattr(v, '__preserve__'):
+        v = v.__preserve__()
+    return v
+
+
+
+ +
+ +
+ + + +

+strip_annotations(v, depth=inf) + +

+ + +
+ +

Exposes depth layers of raw structure of +potentially-Annotated Values. If depth==0 or v is not +Annotated, just returns v. Otherwise, descends recursively +into the structure of v.item.

+
>>> import preserves
+>>> a = preserves.parse('@"A comment" [@a 1 @b 2 @c 3]', include_annotations=True)
+>>> is_annotated(a)
+True
+>>> print(preserves.stringify(a))
+@"A comment" [@a 1 @b 2 @c 3]
+>>> print(preserves.stringify(strip_annotations(a)))
+[1 2 3]
+>>> print(preserves.stringify(strip_annotations(a, depth=1)))
+[@a 1 @b 2 @c 3]
+
+ +
+ Source code in preserves/values.py +
621
+622
+623
+624
+625
+626
+627
+628
+629
+630
+631
+632
+633
+634
+635
+636
+637
+638
+639
+640
+641
+642
+643
+644
+645
+646
+647
+648
+649
+650
+651
+652
+653
+654
+655
+656
+657
+658
+659
+660
+661
+662
+663
+664
+665
def strip_annotations(v, depth=inf):
+    """Exposes `depth` layers of raw structure of
+    potentially-[Annotated][preserves.values.Annotated] `Value`s. If `depth==0` or `v` is not
+    [Annotated][preserves.values.Annotated], just returns `v`. Otherwise, descends recursively
+    into the structure of `v.item`.
+
+    ```python
+    >>> import preserves
+    >>> a = preserves.parse('@"A comment" [@a 1 @b 2 @c 3]', include_annotations=True)
+    >>> is_annotated(a)
+    True
+    >>> print(preserves.stringify(a))
+    @"A comment" [@a 1 @b 2 @c 3]
+    >>> print(preserves.stringify(strip_annotations(a)))
+    [1 2 3]
+    >>> print(preserves.stringify(strip_annotations(a, depth=1)))
+    [@a 1 @b 2 @c 3]
+
+    ```
+    """
+
+    if depth == 0: return v
+    if not is_annotated(v): return v
+
+    next_depth = depth - 1
+    def walk(v):
+        return strip_annotations(v, next_depth)
+
+    v = v.item
+    if isinstance(v, Record):
+        return Record(strip_annotations(v.key, depth), tuple(walk(f) for f in v.fields))
+    elif isinstance(v, list):
+        return tuple(walk(f) for f in v)
+    elif isinstance(v, tuple):
+        return tuple(walk(f) for f in v)
+    elif isinstance(v, set):
+        return frozenset(walk(f) for f in v)
+    elif isinstance(v, frozenset):
+        return frozenset(walk(f) for f in v)
+    elif isinstance(v, dict):
+        return ImmutableDict.from_kvs(walk(f) for f in dict_kvs(v))
+    elif is_annotated(v):
+        raise ValueError('Improper annotation structure')
+    else:
+        return v
+
+
+
+ +
+ + + +
+ +
+ +
+ +
+
+ + + Last update: + March 16, 2023 + +
+ Created: + March 16, 2023 + + +
+
+ + + + + + +
+
+ + +
+ +
+ + + +
+
+
+
+ + + + + + + + + \ No newline at end of file