a `]_-9@sddlmZmZddlmZddlmZddlmZGddde Z e e e e ddZ e idZ idfd d Zd d Zd S))MappingHashable)chain)pvector transformcs@eZdZdZdZfddZeddZeddZd d Z ed d Z d dZ e j Z ddZddZddZddZddZddZddZddZdd Zd!d"Zd#d$Ze jZd%d&ZeZeZeZd'd(Zd)d*Zd+d,Z d-d.Z!d/d0Z"d1d2Z#d3d4Z$d5d6Z%d7d8Z&d9d:Z'd;d<Z(Gd=d>d>e)Z*d?d@Z+Z,S)APMapa Persistent map/dict. Tries to follow the same naming conventions as the built in dict where feasible. Do not instantiate directly, instead use the factory functions :py:func:`m` or :py:func:`pmap` to create an instance. Was originally written as a very close copy of the Clojure equivalent but was later rewritten to closer re-assemble the python dict. This means that a sparse vector (a PVector) of buckets is used. The keys are hashed and the elements inserted at position hash % len(bucket_vector). Whenever the map size exceeds 2/3 of the containing vectors size the map is reallocated to a vector of double the size. This is done to avoid excessive hash collisions. This structure corresponds most closely to the built in dict type and is intended as a replacement. Where the semantics are the same (more or less) the same function names have been used but for some cases it is not possible, for example assignments and deletion of values. PMap implements the Mapping protocol and is Hashable. It also supports dot-notation for element access. Random access and insert is log32(n) where n is the size of the map. The following are examples of some common operations on persistent maps >>> m1 = m(a=1, b=3) >>> m2 = m1.set('c', 3) >>> m3 = m2.remove('a') >>> m1 pmap({'b': 3, 'a': 1}) >>> m2 pmap({'c': 3, 'b': 3, 'a': 1}) >>> m3 pmap({'c': 3, 'b': 3}) >>> m3['c'] 3 >>> m3.c 3 )_size_buckets __weakref__ _cached_hashcs tt||}||_||_|SN)superr__new__r r )clssizebucketsself __class__6/usr/lib64/python3.9/site-packages/pyrsistent/_pmap.pyr/sz PMap.__new__cCs t|t|}||}||fSr )hashlen)rkeyindexbucketrrr _get_bucket5szPMap._get_bucketcCs>t||\}}|r2|D]\}}||kr|Sqt|dSr )rrKeyError)rr_rkvrrr_getitem;s   z PMap._getitemcCst|j|Sr )rr"r rrrrr __getitem__EszPMap.__getitem__cCs8t||\}}|r4|D]\}}||krdSqdSdS)NTF)rr)rrrrr rrr _containsHs zPMap._containscCs||j|Sr )r%r r#rrr __contains__TszPMap.__contains__cCs|Sr )iterkeysrrrr__iter__Ysz PMap.__iter__c CsLz ||WStyF}z$tdt|j||WYd}~n d}~00dS)Nz{0} has no attribute '{1}')rAttributeErrorformattype__name__)rrerrr __getattr__\s zPMap.__getattr__ccs|D]\}}|VqdSr  iteritems)rr rrrrr'dsz PMap.iterkeysccs|D]\}}|VqdSr r0)rrr!rrr itervalueskszPMap.itervaluesccs,|jD] }|r|D]\}}||fVqqdSr )r )rrr r!rrrr1os  zPMap.iteritemscCs t|Sr )rr2r(rrrvaluesusz PMap.valuescCs t|Sr )rr'r(rrrkeysxsz PMap.keyscCs t|Sr )rr1r(rrritems{sz PMap.itemscCs|jSr r r(rrr__len__~sz PMap.__len__cCsdtt|S)Nz pmap({0}))r+strdictr(rrr__repr__sz PMap.__repr__cCs||ur dSt|tstSt|t|kr.dSt|trt|dr\t|dr\|j|jkr\dS|j|jkrldSt| t| kSt|trt| |kSt| t| kS)NTFr ) isinstancerNotImplementedrrhasattrr r r9r1r5rotherrrr__eq__s"     z PMap.__eq__cCs tddS)NzPMaps are not orderable) TypeErrorr>rrr__lt__sz PMap.__lt__cCs|Sr )r:r(rrr__str__sz PMap.__str__cCs"t|dstt||_|jS)Nr )r=r frozensetr1r r(rrr__hash__s z PMap.__hash__cCs|||S)a. Return a new PMap with key and val inserted. >>> m1 = m(a=1, b=2) >>> m2 = m1.set('a', 3) >>> m3 = m1.set('c' ,4) >>> m1 pmap({'b': 2, 'a': 1}) >>> m2 pmap({'b': 2, 'a': 3}) >>> m3 pmap({'c': 4, 'b': 2, 'a': 1}) )evolverset persistentrrvalrrrrGszPMap.setcCs||S)z Return a new PMap without the element specified by key. Raises KeyError if the element is not present. >>> m1 = m(a=1, b=2) >>> m1.remove('a') pmap({'b': 2}) )rFremoverHr#rrrrKs z PMap.removecCs(z ||WSty"|YS0dS)a Return a new PMap without the element specified by key. Returns reference to itself if element is not present. >>> m1 = m(a=1, b=2) >>> m1.discard('a') pmap({'b': 2}) >>> m1 is m1.discard('c') True N)rKrr#rrrdiscards   z PMap.discardcGs|jddg|RS)a* Return a new PMap with the items in Mappings inserted. If the same key is present in multiple maps the rightmost (last) value is inserted. >>> m1 = m(a=1, b=2) >>> m1.update(m(a=2, c=3), {'a': 17, 'd': 35}) pmap({'c': 3, 'b': 2, 'a': 17, 'd': 35}) cSs|Sr r)lrrrrzPMap.update..) update_with)rmapsrrrupdates z PMap.updatecGsN|}|D]8}|D]*\}}||||vr<||||n|qq |S)a# Return a new PMap with the items in Mappings maps inserted. If the same key is present in multiple maps the values will be merged using merge_fn going from left to right. >>> from operator import add >>> m1 = m(a=1, b=2) >>> m1.update_with(add, m(a=2)) pmap({'b': 2, 'a': 3}) The reverse behaviour of the regular merge. Keep the leftmost element instead of the rightmost. >>> m1 = m(a=1) >>> m1.update_with(lambda l, r: l, m(a=2), {'a':3}) pmap({'a': 1}) )rFr5rGrH)rZ update_fnrRrFmaprvaluerrrrQs &zPMap.update_withcCs ||Sr )rSr>rrr__add__sz PMap.__add__cCstt|ffSr )pmapr9r(rrr __reduce__szPMap.__reduce__cGs t||S)a Transform arbitrarily complex combinations of PVectors and PMaps. A transformation consists of two parts. One match expression that specifies which elements to transform and one transformation function that performs the actual transformation. >>> from pyrsistent import freeze, ny >>> news_paper = freeze({'articles': [{'author': 'Sara', 'content': 'A short article'}, ... {'author': 'Steve', 'content': 'A slightly longer article'}], ... 'weather': {'temperature': '11C', 'wind': '5m/s'}}) >>> short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:25] + '...' if len(c) > 25 else c) >>> very_short_news = news_paper.transform(['articles', ny, 'content'], lambda c: c[:15] + '...' if len(c) > 15 else c) >>> very_short_news.articles[0].content 'A short article' >>> very_short_news.articles[1].content 'A slightly long...' When nothing has been transformed the original data structure is kept >>> short_news is news_paper True >>> very_short_news is news_paper False >>> very_short_news.articles[0] is news_paper.articles[0] True r)rZtransformationsrrrrszPMap.transformcCs|Sr rr(rrrcopysz PMap.copyc@sheZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddZdS)z PMap._Evolver)_buckets_evolverr _original_pmapcCs||_|j|_|j|_dSr )r[r rFrZr )rZ original_pmaprrr__init__s zPMap._Evolver.__init__cCst|j|Sr )rr"rZr#rrrr$"szPMap._Evolver.__getitem__cCs|||dSr )rGrIrrr __setitem__%szPMap._Evolver.__setitem__cst|jd|jkr(|dt|j|f}t|j|\}}|r|D]>\}|krJ|urfdd|D}||j|<|SqJ|g}||||j|<|jd7_n|g|j|<|jd7_|S)Ngq= ףp?cs(g|] \}}|kr||fn|fqSrr).0Zk2Zv2r rJrr 2rPz%PMap._Evolver.set..)rrZr _reallocaterrextend)rrrJZkvrrr! new_bucketrr`rrG(s$      zPMap._Evolver.setcCs|dg}|j}tdd|DD]>\}}t||}||rX||||fq(||fg||<q(t|_|j|dS)Ncss|]}|r|VqdSr r)r_xrrr DrPz,PMap._Evolver._reallocate..) rZrHr from_iterablerappendrrFrd)rZnew_sizeZnew_listrr r!rrrrrcAs    zPMap._Evolver._reallocatecCs |jSr )rZis_dirtyr(rrrrjPszPMap._Evolver.is_dirtycCs"|rt|j|j|_|jSr )rjrr rZrHr[r(rrrrHSszPMap._Evolver.persistentcCs|jSr r6r(rrrr7YszPMap._Evolver.__len__cCst|j|Sr )rr%rZr#rrrr&\szPMap._Evolver.__contains__cCs||dSr )rKr#rrr __delitem___szPMap._Evolver.__delitem__csnt|j\}}|r\fdd|D}t|t|kr\|r@|nd|j|<|jd8_|StddS)Ncs g|]\}}|kr||fqSrr)r_r r!rrrrafrPz(PMap._Evolver.remove..rbz{0})rrrZrr rr+)rrrrrerrlrrKbszPMap._Evolver.removeN)r- __module__ __qualname__ __slots__r\r$r]rGrcrjrHr7r&rkrKrrrr_EvolversrpcCs ||S)a) Create a new evolver for this pmap. For a discussion on evolvers in general see the documentation for the pvector evolver. Create the evolver and perform various mutating updates to it: >>> m1 = m(a=1, b=2) >>> e = m1.evolver() >>> e['c'] = 3 >>> len(e) 3 >>> del e['a'] The underlying pmap remains the same: >>> m1 pmap({'b': 2, 'a': 1}) The changes are kept in the evolver. An updated pmap can be created using the persistent() function on the evolver. >>> m2 = e.persistent() >>> m2 pmap({'c': 3, 'b': 2}) The new pmap will share data with the original pmap in the same way that would have been done if only using operations on the pmap. )rpr(rrrrFnsz PMap.evolver)-r-rmrn__doc__ror staticmethodrr"r$r%r&rgetr)r/r'r2r1r3r4r5r7r:r@__ne__rB__le____gt____ge__rCrErGrKrLrSrQrVrXrrYobjectrprF __classcell__rrrrrsR%      Trc Cs|r |}n,zdt|pd}Wnty4d}Yn0|dg}t|tsRt|}|D]B\}}t|}||}||}|r|||fqZ||fg||<qZtt|t |S)Nr^) r Exceptionr;rr9r5rrirrrd) initialpre_sizerrr r!hrrrrr_turbo_mappings"    rcCs|stSt||S)a Create new persistent map, inserts all elements in initial into the newly created map. The optional argument pre_size may be used to specify an initial size of the underlying bucket vector. This may have a positive performance impact in the cases where you know beforehand that a large number of elements will be inserted into the map eventually since it will reduce the number of reallocations required. >>> pmap({'a': 13, 'b': 14}) pmap({'b': 14, 'a': 13}) ) _EMPTY_PMAPr)r|r}rrrrWs rWcKst|S)z Creates a new persitent map. Inserts all key value arguments into the newly created map. >>> m(a=13, b=14) pmap({'b': 14, 'a': 13}) )rW)kwargsrrrmsrN)collections.abcrr itertoolsrZpyrsistent._pvectorrZpyrsistent._transformationsrrxrregisterrrrWrrrrrs