& dDhUddlmZmZmZmZmZmZddlZddlm Z m Z m Z m Z m Z eefZe edfed<eddDZGdd ZGd d Zej,eej,ey) )MutableMappingMappingMutableSequenceIteratorSequence ContainerN)TupleAnyDictSetList.str_typec# K|]}|ywN).0_s 3/usr/lib/python3/dist-packages/pyparsing/results.py rsas rcJeZdZUedefed<dgZdddefdZdZdZ dZ y ) _ParseResultsWithOffset ParseResultstupp1p2c||f|_yrr)selfrrs r__init__z _ParseResultsWithOffset.__init__s .0"Xc |j|Srrris r __getitem__z#_ParseResultsWithOffset.__getitem__sxx{r c|jSrrrs r __getstate__z$_ParseResultsWithOffset.__getstate__s xxr c|d|_yNrr)rargss r __setstate__z$_ParseResultsWithOffset.__setstate__s 7r N) __name__ __module__ __qualname__r int__annotations__ __slots__rr$r'r+rr rrrs; ~s" ##I6>6s6r rceZdZUdZdgdfZeedfed<eed<ded<e eed<e ed <e eed <e eefed <d Z Gd deZ d8dZddddefdZdZefdZdZde fdZdefdZde fdZdefdZdefdZdZdZdZde fdZdZ d9d Z!d!Z"d"Z#d#Z$d$Z%d%Z&d:d&Z'd:d'Z(d;d(Z)defd)Z*defd*Z+dra{Structured parse results, to provide multiple means of access to the parsed data: - as a list (``len(results)``) - by list index (``results[0], results[1]``, etc.) - by attribute (``results.`` - see :class:`ParserElement.set_results_name`) Example:: integer = Word(nums) date_str = (integer.set_results_name("year") + '/' + integer.set_results_name("month") + '/' + integer.set_results_name("day")) # equivalent form: # date_str = (integer("year") + '/' # + integer("month") + '/' # + integer("day")) # parse_string returns a ParseResults object result = date_str.parse_string("1999/12/31") def test(s, fn=repr): print(f"{s} -> {fn(eval(s))}") test("list(result)") test("result[0]") test("result['month']") test("result.day") test("'month' in result") test("'minutes' in result") test("result.dump()", str) prints:: list(result) -> ['1999', '/', '12', '/', '31'] result[0] -> '1999' result['month'] -> '12' result.day -> '31' 'month' in result -> True 'minutes' in result -> False result.dump() -> ['1999', '/', '12', '/', '31'] - day: '31' - month: '12' - year: '1999' Nr. _null_values_name_parent _all_names_modal_toklist_tokdict)r4r5r6r7r8r9ceZdZdZddZy)ParseResults.Lista Simple wrapper class to distinguish parsed list results that should be preserved as actual Python lists, instead of being converted to :class:`ParseResults`:: LBRACK, RBRACK = map(pp.Suppress, "[]") element = pp.Forward() item = ppc.integer element_list = LBRACK + pp.DelimitedList(element) + RBRACK # add parse actions to convert from ParseResults to actual Python collection types def as_python_list(t): return pp.ParseResults.List(t.as_list()) element_list.add_parse_action(as_python_list) element <<= item | element_list element.run_tests(''' 100 [2,3,4] [[2, 1],3,4] [(2, 1),3,4] (2,3,4) ''', post_parse=lambda s, r: (r[0], type(r[0]))) prints:: 100 (100, ) [2,3,4] ([2, 3, 4], ) [[2, 1],3,4] ([[2, 1], 3, 4], ) (Used internally by :class:`Group` when `aslist=True`.) Nc|g}t|ts-t|jdt |jtj |S)Nz* may only be constructed with a list, not ) isinstancelist TypeErrorr,type__new__)cls containeds rrAzParseResults.List.__new__sT  i.||n$NtT]OgOgNhi<<$ $r r)r,r-r.__doc__rArr rr r;bs $ L %r r c ^t|tr|Stj|}d|_d|_t |_|g|_nOt|ttfr1t|tjr|ddgn t||_n|g|_t|_ |Sr)r=robjectrAr4r5setr6r8r>_generator_typer dictr9)rBtoklistnamekwargsrs rrAzParseResults.__new__s g| ,N~~c"  % ?DM $!8 9g|'8'89 '] M %IDM  r Tc|||_||dk7r||tr t|}|s|h|_||_||j vrx||t tfr|g}|rV||tr#tt|jd||<ntt|dd||<|||_y |d||<yyyy#tttf$r||ur|||<Yy||_YywxYw)Nr)r7r/strr6r4r3rr@rrr8KeyErrorr? IndexError)rrJrKasListmodalr=s rrzParseResults.__init__s     $$4y#'&DJd///g$'78&iG!'<8%<()9)9:A&T &=(4a&T (,DJ$.%,QZT 0 !+ ,%i<."$.)0DJ)-DJ .s7CC,"C,+C,ct|ttfr|j|S||jvr|j |ddSt |j |Dcgc]}|d c}Scc}w)Nr)r=r/slicer8r6r9r)rr#vs rr$zParseResults.__getitem__sj a#u &==# #'}}Q'+A..#4==3C$DaQqT$DEE$Ds A2c||tr;|jj|t|gz|j|<|d}nf||tt fr||j |<|}nA|jj|tt|dgz|j|<|}||tr||_yyr)) rr9getr>r/rVr8rr5)rkrWr=subs r __setitem__zParseResults.__setitem__s a0 1#}}00DF;qcADMM! A$C C< ( DMM! C#}}00DF;'1-? DMM! C c< (CK )r c t|ttfrt|j}|j|=t|tr|dkr||z }t||dz}t t |j|}|j|jjD]7\}}|D]-}t|D]\}\}} t|| | |kDz ||</9y|j|=y)Nr) r=r/rVlenr8r>rangeindicesreverser9items enumerater) rr#mylenremovedrK occurrencesjrZvaluepositions r __delitem__zParseResults.__delitem__s a#u & &E a !S!q5JA!QUO5!))E"234G OO %)]]%8%8%: !k A09+0F,,E8)@!8x!|#<* A  a r returnc||jvSrr9)rrZs r __contains__zParseResults.__contains__sDMM!!r c,t|jSr)r_r8r&s r__len__zParseResults.__len__s4==!!r c:|jxs |j Sr)r8r9r&s r__bool__zParseResults.__bool__s 6777r c,t|jSriterr8r&s r__iter__zParseResults.__iter__DMM""r c8t|jdddS)NrUrur&s r __reversed__zParseResults.__reversed__sDMM$B$'((r c,t|jSr)rvr9r&s rkeyszParseResults.keys rxr c6fdjDS)Nc3(K|] }| ywrrrrZrs rrz&ParseResults.values..s-AQ-sr|r&s`rvalueszParseResults.values s---r c6fdjDS)Nc3,K|] }||f ywrrrs rrz%ParseResults.items..s2DG 2srr&s`rrczParseResults.itemss2diik22r c|j S)z Since ``keys()`` returns an iterator, this method is helpful in bypassing code that looks for the existence of any defined results names.rnr&s rhaskeyszParseResults.haskeyss}}$$$r c|sdg}|jD]\}}|dk(r|d|f}td|t|dtst |dk(s|d|vr|d}||}||=|S|d}|S)a Removes and returns item at specified index (default= ``last``). Supports both ``list`` and ``dict`` semantics for ``pop()``. If passed no argument or an integer argument, it will use ``list`` semantics and pop tokens from the list of parsed tokens. If passed a non-integer argument (most likely a string), it will use ``dict`` semantics and pop the corresponding value from any defined results names. A second default return value argument is supported, just as in ``dict.pop()``. Example:: numlist = Word(nums)[...] print(numlist.parse_string("0 123 321")) # -> ['0', '123', '321'] def remove_first(tokens): tokens.pop(0) numlist.add_parse_action(remove_first) print(numlist.parse_string("0 123 321")) # -> ['123', '321'] label = Word(alphas) patt = label("LABEL") + Word(nums)[1, ...] print(patt.parse_string("AAB 123 321").dump()) # Use pop() in a parse action to remove named result (note that corresponding value is not # removed from list form of results) def remove_LABEL(tokens): tokens.pop("LABEL") return tokens patt.add_parse_action(remove_LABEL) print(patt.parse_string("AAB 123 321").dump()) prints:: ['AAB', '123', '321'] - LABEL: 'AAB' ['AAB', '123', '321'] rUdefaultrz)pop() got an unexpected keyword argument r^)rcr?r=r/r_)rr*rLrZrWindexret defaultvalues rpopzParseResults.popsP4DLLN SDAqI~Q|"KA5 QRR  S d1gs #s4yA~aDGEu+CU J7L r c||vr||S|S)a^ Returns named result matching the given key, or if there is no such name, then returns the given ``default_value`` or ``None`` if no ``default_value`` is specified. Similar to ``dict.get()``. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parse_string("1999/12/31") print(result.get("year")) # -> '1999' print(result.get("hour", "not specified")) # -> 'not specified' print(result.get("hour")) # -> None r)rkey default_values rrYzParseResults.getQs$ $;9  r c|jj|||jjD]0\}}t |D]\}\}}t ||||kDz||<2y)a; Inserts new element at location index in the list of parsed tokens. Similar to ``list.insert()``. Example:: numlist = Word(nums)[...] print(numlist.parse_string("0 123 321")) # -> ['0', '123', '321'] # use a parse action to insert the parse location in the front of the parsed results def insert_locn(locn, tokens): tokens.insert(0, locn) numlist.add_parse_action(insert_locn) print(numlist.parse_string("0 123 321")) # -> [0, '0', '123', '321'] N)r8insertr9rcrdr)rr ins_stringrKrgrZrirjs rrzParseResults.inserthst" UJ/!%!4!4!6  D+(1+(> $$E8!88x%'78" A  r c:|jj|y)a Add single element to end of ``ParseResults`` list of elements. Example:: numlist = Word(nums)[...] print(numlist.parse_string("0 123 321")) # -> ['0', '123', '321'] # use a parse action to compute the sum of the parsed integers, and add it to the end def append_sum(tokens): tokens.append(sum(map(int, tokens))) numlist.add_parse_action(append_sum) print(numlist.parse_string("0 123 321")) # -> ['0', '123', '321', 444] N)r8append)ritems rrzParseResults.appends T"r c~t|tr|j|y|jj |y)a Add sequence of elements to end of ``ParseResults`` list of elements. Example:: patt = Word(alphas)[1, ...] # use a parse action to append the reverse of the matched strings, to make a palindrome def make_palindrome(tokens): tokens.extend(reversed([t[::-1] for t in tokens])) return ''.join(tokens) patt.add_parse_action(make_palindrome) print(patt.parse_string("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl' N)r=r__iadd__r8extend)ritemseqs rrzParseResults.extends, g| , MM' " MM  )r cV|jdd=|jjy)z7 Clear all elements and results names. N)r8r9clearr&s rrzParseResults.clears  MM!  r cd ||S#t$r|jdr t|YywxYw)N__rN)rP startswithAttributeError)rrKs r __getattr__zParseResults.__getattr__s: :  t$$T** s %//c0|j}||z }|Sr)copy)rotherrs r__add__zParseResults.__add__siik u  r c|s|S|jrt|jfd}|jj}|Dcgc]&\}}|D]}|t |d||df(}}}}|D](\}}|||<t |dt s||d_*|xj|jz c_|xj|jzc_|Scc}}}w)Nc|dkrS|zSr)r)aoffsets rz'ParseResults.__iadd__..sAE&q6zr rr^) r9r_r8rcrr=rr5r6) rr addoffset otheritemsrZvlistrWotherdictitemsrs @rrzParseResults.__iadd__sK >>'FAI--/J!+Au+AaD)AaD/BCCN ' (1QadL1#'AaDL ( '  5+++ s +C(cVt|tr|dk(r|jS||zSr))r=r/r)rrs r__radd__zParseResults.__radd__s* eS !eqj99; 4< r cnt|jd|jd|jdS)N(, ))r@r,r8as_dictr&s r__repr__zParseResults.__repr__s2t*%%&a '84<<>:J!LLr c ddj|jDcgc](}t|tr t |n t |*c}zdzScc}w)N[r])joinr8r=rrOreprr"s r__str__zParseResults.__str__s\ ii"]])L9CFtAwF   s-A cg}|jD]U}|r|r|j|t|tr||j z }<|jt |W|Sr)r8rr=r _asStringListrO)rsepoutrs rrzParseResults._asStringLists^MM &Ds 3$ -t))++ 3t9%  & r c|jDcgc]$}t|tr|jn|&c}Scc}w)ax Returns the parse results as a nested list of matching tokens, all converted to strings. Example:: patt = Word(alphas)[1, ...] result = patt.parse_string("sldkj lsdkj sldkj") # even though the result prints in string-like form, it is actually a pyparsing ParseResults print(type(result), result) # -> ['sldkj', 'lsdkj', 'sldkj'] # Use as_list() to create an actual list result_list = result.as_list() print(type(result_list), result_list) # -> ['sldkj', 'lsdkj', 'sldkj'] )r8r=ras_list)rress rrzParseResults.as_lists<"}} (\:CKKM C   s);cRfdtfd|jDS)a Returns the named parse results as a nested dictionary. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parse_string('12/31/1999') print(type(result), repr(result)) # -> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]}) result_dict = result.as_dict() print(type(result_dict), repr(result_dict)) # -> {'day': '1999', 'year': '12', 'month': '31'} # even though a ParseResults supports dict-like access, sometime you just need to have a dict import json print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable print(json.dumps(result.as_dict())) # -> {"month": "31", "day": "1999", "year": "12"} ct|tr6|jr|jS|Dcgc] }| c}S|Scc}wr)r=rrr)objrWto_items rrz%ParseResults.as_dict..to_itemsA#|,(+ s{{}TPS;T1GAJ;TT .!s=1Q O=s)rIrc)rrs @rrzParseResults.as_dicts!*  = ===r ct|j}|jj|_|j|_|xj |j zc_|j |_|S)a Returns a new shallow copy of a :class:`ParseResults` object. `ParseResults` items contained within the source are shared with the copy. Use :class:`ParseResults.deepcopy()` to create a copy with its own separate content values. )rr8r9rr5r6r4)rrs rrzParseResults.copy#sS4==)}}))+ ll  $//)JJ  r c0|j}t|jD]\}}t|tr|j |j|<4t|t tfrKt|tr]t|x|j|<}|jD]*\}}t|tr|j n|||<,t|tst|d|D|j|<|S)zL Returns a new deep copy of a :class:`ParseResults` object. c3`K|]&}t|tr|jn|(ywr)r=rdeepcopy)rrWs rrz(ParseResults.deepcopy..As)-KLJq,$?AJJLQF-s,.) rrdr8r=rrrObytesrr@rcr)rrr#rdestrZrWs rrzParseResults.deepcopy1siik . FAs#|,#&<<> a C#u.C0*3$s)+5 a 4IIKQDAq.8L.IajjlqDGQC+#,49-PS-$ a   r cjr jSjr;j}|jj}t fd|DdSt dk(rxt jdk(r`t t jjdddvr,t t jjSy)a Returns the results name for this token expression. Useful when several different expressions might match at a particular location. Example:: integer = Word(nums) ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d") house_number_expr = Suppress('#') + Word(nums, alphanums) user_data = (Group(house_number_expr)("house_number") | Group(ssn_expr)("ssn") | Group(integer)("age")) user_info = user_data[1, ...] result = user_info.parse_string("22 111-22-3333 #221B") for item in result: print(item.get_name(), ':', item[0]) prints:: age : 22 ssn : 111-22-3333 house_number : 221B c3DK|]\}}|D] \}}|ur|ywrr)rrZrrWlocrs rrz(ParseResults.get_name..es= 5"'3Dys Nr^r)rrU) r4r5r9rcnextr_rvrr|)rparparent_tokdict_itemss` rget_namezParseResults.get_nameFs2 ::::  \\"&,,C#&<<#5#5#7 $8   INDMM"a'T$--..01215a8GCT]]//123 3r cg}d}|j|r|t|jznd|r|jrt d|j D}|D]\}} |r|j||j|d|zd|dt | trE| r(|j| j||||dzo|jt| |jt| td |Dr|} t| D]\} } t | trE|jd j|d|z| |d|dzz| j||||dz[|jd |d|z| |d|dzzt| fzdj|S) aM Diagnostic method for listing out the contents of a :class:`ParseResults`. Accepts an optional ``indent`` argument so that this string can be embedded in a nested display of other data. Example:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parse_string('1999/12/31') print(result.dump()) prints:: ['1999', '/', '12', '/', '31'] - day: '31' - month: '12' - year: '1999'  rNc3<K|]\}}t||fywr)rO)rrZrWs rrz$ParseResults.dump..sDtq!A{Dz z- z: r^)indentfull include_list_depthc3<K|]}t|tywr)r=r)rvvs rrz$ParseResults.dump..s?B:b,/?rz {}{}[{}]: {}{}{}z %s%s[%d]: %s%s%s)rrOrrsortedrcr=rdumpranyrdformatr) rrrrrrNLrcrZrWr#rs rrzParseResults.dumpvs*  <6C //RH ||~Dtzz|DD!,DAq 2JJ&4&=):"QCrBC!!\2JJ !+1)-1=+1A: !'!" JJs1v. 47+#,$?$??&q\EAr!"l3 188 &!% ! &!%!!4 "+1)-1=+1A: !(!"   1 &!% ! &!%!!4 #B  %<wws|r cRtj|jg|i|y)a$ Pretty-printer for parsed results as a list, using the `pprint `_ module. Accepts additional positional or keyword args as defined for `pprint.pprint `_ . Example:: ident = Word(alphas, alphanums) num = Word(nums) func = Forward() term = ident | num | Group('(' + func + ')') func <<= ident + Group(Optional(DelimitedList(term))) result = func.parse_string("fna a,b,(fnb c,d,200),100") result.pprint(width=40) prints:: ['fna', ['a', 'b', ['(', 'fnb', ['c', 'd', '200'], ')'], '100']] N)pprintr)rr*rLs rrzParseResults.pprints 2  dlln6t6v6r c~|j|jjd|j|jffSr)r8r9rr6r4r&s rr'zParseResults.__getstate__s9 MM ""$    r cd|\|_\|_}}|_t||_d|_yr)r8r9r4rGr6r5)rstater inAccumNamess rr+zParseResults.__setstate__s.HME E sL$*l+ r c2|j|jfSr)r8r4r&s r__getnewargs__zParseResults.__getnewargs__s}}djj((r c^tt|t|jzSr)dirr@r>r|r&s r__dir__zParseResults.__dir__s 4:diik!222r c d}|g}|jD]A\}}t|tr||j||z }-|||g|||z }C| ||g|}|S)z Helper classmethod to construct a ``ParseResults`` from a ``dict``, preserving the name-value relations as results names. If an optional ``name`` argument is given, a nested ``ParseResults`` will be returned. cZ t|t|t S#t$rYywxYw)NF)rvr=r Exception)rs r is_iterablez+ParseResults.from_dict..is_iterables4 5S &c8444   s  **)rK)rKrR)rcr=r from_dict)rBrrKrrrZrWs rrzParseResults.from_dicts 5"gKKM ?DAq!W%s}}QQ}//sA3Q{1~>>  ?  se$'C r )NNr)rrrlr)rlr)rN)rNTTr)>r,r-r.rDr3r r r0rOr boolr r r1r>rAr=rr$r\rkror/rqrsrrwrzr|rrcrrrYrrrrrrrrrrrrrIrrrrrrr'r+rr classmethodrrRasDictgetNamerr rrr"s+Z&*2rNL%S/2 J C L3i38nI0%t0%d0d$:.BF,6 !.""""8$8#(#)h)#.3%% 6 p!.2#"*( , M#M       (>>: *.`NN`78   )34F+ F+G,r r)collections.abcrrrrrrrtypingr r r r r rOrrr@r0rHrrregisterrr rrs}..!5\%c )2'"v -v -r %&r