K ilUddlmZddlZddlmZmZmZmZmZddl Z ddl m Z ddl m Z eefZded<ed d DZGd d ZGd dZej,eej,ey)) annotationsN)MutableMappingMappingMutableSequenceIteratorIterable)Any)replaced_by_pep8ztuple[type, ...]str_typec# K|]}|ywN).0_s W/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/pyparsing/results.py rsas rc8eZdZUded<dgZddZdZdZdZy) _ParseResultsWithOffsetztuple[ParseResults, int]tupc||f|_yrr)selfp1p2s r__init__z _ParseResultsWithOffset.__init__s .0"Xc |j|Srrris r __getitem__z#_ParseResultsWithOffset.__getitem__sxx{rc|jSrrrs r __getstate__z$_ParseResultsWithOffset.__getstate__!s xxrc|d|_yNrr)rargss r __setstate__z$_ParseResultsWithOffset.__setstate__$s 7rN)r ParseResultsrintreturnNone) __name__ __module__ __qualname____annotations__ __slots__rr!r$r(rrrrrs# !!I6rrceZdZUdZdgdfZded<ded<ded<d ed <d ed <d ed<ded<dZGddeZd>dZ dddde f d?dZ dZ e fdZ dZd@dZdAdZd@dZdBdZdBdZdZd Zd!Zd@d"Zd#ZdCd$Zd%Zd&Zd'Zd(Zd)ZdDd*ZdDd+Z dEd,Z!dFd-Z"dFd.Z#dGd/Z$d0d1dHd2Z%dId3Z&dEd4Z'dEd5Z(dJd6Z)dKdFd7Z*d8Z+d9Z,d:Z-d;Z.d<Z/e0dCdEd=Z1e%Z2 e&Z3 e)Z4y)Lr)aStructured 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: .. testcode:: 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: .. testoutput:: 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' Nrztuple[Any, ...] _null_valuesstr_name_parentzset[str] _all_namesbool_modalz list[Any]_toklistzdict[str, Any]_tokdict)r5r6r7r9r:r;ceZdZdZddZy)ParseResults.Lista9 Simple wrapper class to distinguish parsed list results that should be preserved as actual Python lists, instead of being converted to :class:`ParseResults`: .. testcode:: import pyparsing as pp ppc = pp.common LBRACK, RBRACK, LPAR, RPAR = pp.Suppress.using_each("[]()") element = pp.Forward() item = ppc.integer item_list = pp.DelimitedList(element) element_list = LBRACK + item_list + RBRACK | LPAR + item_list + RPAR element <<= item | element_list # add parse action to convert from ParseResults # to actual Python collection types @element_list.add_parse_action def as_python_list(t): return pp.ParseResults.List(t.as_list()) element.run_tests(''' 100 [2,3,4] [[2, 1],3,4] [(2, 1),3,4] (2,3,4) ([2, 3], 4) ''', post_parse=lambda s, r: (r[0], type(r[0])) ) prints: .. testoutput:: :options: +NORMALIZE_WHITESPACE 100 (100, ) [2,3,4] ([2, 3, 4], ) [[2, 1],3,4] ([[2, 1], 3, 4], ) [(2, 1),3,4] ([[2, 1], 3, 4], ) (2,3,4) ([2, 3, 4], ) ([2, 3], 4) ([[2, 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 rrCzParseResults.List.__new__sT  i.||n$NtT]OgOgNhi<<$ $rr)r-r.r/__doc__rCrrrListr=ns 9 v %rrGc ^t|tr|Stj|}d|_d|_t |_|g|_nOt|ttfr1t|tjr|ddgn t||_n|g|_t|_ |Sr)r?r)objectrCr5r6setr7r:r@_generator_typerGdictr;)rDtoklistnamekwargsrs rrCzParseResults.__new__s g| ,N~~c"  % ?DM $!8 9g|'8'89 '] M %IDM  rTc|||_||dk(ry||tr t|}|s|h|_||_||j vry||t tfr|g}|rV||tr#tt|jd||<ntt|dd||<|||_y |d||<y#tttf$r||ur|||<Yy||_YywxYw)Nr)r9r*r4r7r5r3r rBr)rr:KeyErrorrA IndexError)rrMrNasListmodalr?s rrzParseResults.__init__s  <42:  dC t9D#fDO d'' '  g$/ 0iG '<04\'BRBR5SUVWT 4\'!*5MqQT #DJ   " DJ)Z0 "d"$T !  "s9CC+!C+*C+ct|ttfr|j|S||jvr|j |ddSt |j |Dcgc]}|d c}Scc}w)Nr)r?r*slicer:r7r;r))rr vs rr!zParseResults.__getitem__sj a#u &==# # DOO #==#B'* *4==+;.6s-AQ-sr}r#s`rrdzParseResults.values5s---rc6fdjDS)Nc3,K|] }||f ywrrrs rrz%ParseResults.items..9s2DG 2srr#s`ritemszParseResults.items8s2diik22rc|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.haskeys;s}}$$$rc|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: .. doctest:: >>> 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) [W:(0-9)]... >>> 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()) ['AAB', '123', '321'] - LABEL: 'AAB' >>> # 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) {W:(A-Za-z) {W:(0-9)}...} >>> print(patt.parse_string("AAB 123 321").dump()) ['AAB', '123', '321'] rWdefaultrz)pop() got an unexpected keyword argument r )rrAr?r*r`)rr'rOr\rYindexret defaultvalues rpopzParseResults.popAs\4DLLN SDAqI~Q|"KA5 QRR  S d1gs #s4yA~aDGEu+CU J7L rc||vr||S|S)as 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: .. doctest:: >>> integer = Word(nums) >>> date_str = integer("year") + '/' + integer("month") + '/' + integer("day") >>> result = date_str.parse_string("1999/12/31") >>> result.get("year") '1999' >>> result.get("hour", "not specified") 'not specified' >>> result.get("hour") r)rkey default_values rr[zParseResults.gets. $;9  rc|jj|||jjD]-}t |D]\}\}}t ||||kDz||</y)a Inserts new element at location index in the list of parsed tokens. Similar to ``list.insert()``. Example: .. doctest:: >>> 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) [W:(0-9)]... >>> print(numlist.parse_string("0 123 321")) [0, '0', '123', '321'] N)r:insertr;rdrer)rr ins_stringrhr\rjrks rrzParseResults.insertso2 UJ/==//1 K(1+(> $$E8!88x%'78" A  rc:|jj|y)a Add single element to end of ``ParseResults`` list of elements. Example: .. doctest:: >>> 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) [W:(0-9)]... >>> print(numlist.parse_string("0 123 321")) ['0', '123', '321', 444] N)r:append)ritems rrzParseResults.appends, T"rc~t|tr|j|y|jj |y)as Add sequence of elements to end of :class:`ParseResults` list of elements. Example: .. testcode:: 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")) prints: .. testoutput:: ['lskdjsdlkjflksddsklfjkldsjdksl'] N)r?r)__iadd__r:extend)ritemseqs rrzParseResults.extends,2 g| , MM' " MM  )rcV|jdd=|jjy)z7 Clear all elements and results names. N)r:r;clearr#s rrzParseResults.clears  MM!  rcd ||S#t$r|jdr t|YywxYw)N__rQ)rR startswithAttributeError)rrNs r __getattr__zParseResults.__getattr__s: :  t$$T** s %//c0|j}||z }|Sr)copy)rotherrs r__add__zParseResults.__add__siik u  rc|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&q6zrrr ) r;r`r:rrr?r)r6r7) rr addoffset otheritemsr\vlistrYotherdictitemsrs @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< rcnt|jd|jd|jdS)N(, ))rBr-r:as_dictr#s r__repr__zParseResults.__repr__$s2t*%%&a '84<<>:J!LLrc ddj|jDcgc](}t|tr t |n t |*c}zdzScc}w)N[r])joinr:r?r)r4reprrs r__str__zParseResults.__str__'s\ ii"]])L9CFtAwF   s-A cg}|jD]U}|r|r|j|t|tr||j z }<|jt |W|Sr)r:rr?r) _asStringListr4)rsepoutrs rrzParseResults._asStringList3s^MM &Ds 3$ -t))++ 3t9%  & rF)flattencfd}|r g|SjDcgc]$}t|tr|jn|&c}Scc}w)a Returns the parse results as a nested list of matching tokens, all converted to strings. If ``flatten`` is True, all the nesting levels in the returned list are collapsed. Example: .. doctest:: >>> 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 >>> type(result) >>> print(result) ['sldkj', 'lsdkj', 'sldkj'] .. doctest:: >>> # Use as_list() to create an actual list >>> result_list = result.as_list() >>> type(result_list) >>> print(result_list) ['sldkj', 'lsdkj', 'sldkj'] .. versionchanged:: 3.2.0 New ``flatten`` argument. c3Ktjg}|r@|j}t|tr|j |dddn||r?yywrz) collectionsdequepopleftr?r) extendleft)prto_visitto_dors r flattenedz'ParseResults.as_list..flattened]sV"((41H ((*e\2''dd 4K s AAA)r:r?r)as_list)rrrress` rrzParseResults.as_list>sV>  %Yt_% % ==",C!> CG s)A cRfdtfd|jDS)ac Returns the named parse results as a nested dictionary. Example: .. doctest:: >>> integer = pp.Word(pp.nums) >>> date_str = integer("year") + '/' + integer("month") + '/' + integer("day") >>> result = date_str.parse_string('1999/12/31') >>> type(result) >>> result ParseResults(['1999', '/', '12', '/', '31'], {'year': '1999', 'month': '12', 'day': '31'}) >>> result_dict = result.as_dict() >>> type(result_dict) >>> result_dict {'year': '1999', 'month': '12', 'day': '31'} >>> # even though a ParseResults supports dict-like access, >>> # sometime you just need to have a dict >>> import json >>> print(json.dumps(result)) Traceback (most recent call last): TypeError: Object of type ParseResults is not JSON serializable >>> print(json.dumps(result.as_dict())) {"year": "1999", "month": "12", "day": "31"} ct|tr6|jr|jS|Dcgc] }| c}S|Scc}wr)r?r)rr)objrYto_items rrz%ParseResults.as_dict..to_itemsA#|,(+ s{{}TPS;T1GAJ;TT .s=1Q O=s)rLr)rrs @rrzParseResults.as_dictns"B  = ===rct|j}|jj|_|j|_|xj |j zc_|j |_|S)a Returns a new shallow copy of a :class:`ParseResults` object. :class:`ParseResults` items contained within the source are shared with the copy. Use :meth:`ParseResults.deepcopy` to create a copy with its own separate content values. )r)r:r;rr6r7r5)rrs rrzParseResults.copysS4==)}}))+ ll  $//)JJ  rc0|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)zm Returns a new deep copy of a :class:`ParseResults` object. .. versionadded:: 3.1.0 c3`K|]&}t|tr|jn|(ywr)r?r)deepcopy)rrYs rrz(ParseResults.deepcopy..s),KLJq,$?AJJLQF,s,.) rrer:r?r)rr4bytesrrBrr)rrr rdestr\rYs rrzParseResults.deepcopys iik . FAs#|,"%,,. QC#u.C0)2c4 Q$IIKQDAq.8L.IajjlqDGQC*"+$s),PS,# Q  rcjr jSjr;j}|jj}t fd|DdSt dk(rxt jdk(r`t t jjdddvr,t t jjSy)aG Returns the results name for this token expression. Useful when several different expressions might match at a particular location. Example: .. testcode:: 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: .. testoutput:: age : 22 ssn : 111-22-3333 house_number : 221B c3DK|]\}}|D] \}}|ur|ywrr)rr\rrYlocrs rrz(ParseResults.get_name..s= 5"'3Dys Nr r)rrW) r5r6r;rnextr`rvrdr})rparparent_tokdict_itemss` rget_namezParseResults.get_names@ ::::  \\ $ C#&<<#5#5#7 $8   INDMM"a'T$--..01215a8GCT]]//123 3rcg}d}|j|r|t|jznd|sdj|S|j rt d|j D}|D]\}} |r|j||j|d|zd|dt| ts|jt| `| s|jt| }|j| j||||dztd |Dsdj|S|} d} d} t| D]\} } t| trE| j||||dz}|j| || |zd | d | || |dzz| [|j| || |zd | d | || |dzz| dj|S) as 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: .. testcode:: integer = Word(nums) date_str = integer("year") + '/' + integer("month") + '/' + integer("day") result = date_str.parse_string('1999/12/31') print(result.dump()) prints: .. testoutput:: ['1999', '/', '12', '/', '31'] - day: '31' - month: '12' - year: '1999'  rQc3<K|]\}}t||fywr)r4)rr\rYs rrz$ParseResults.dump..s@41aCFA;@z z- z: r )indentfull include_list_depthc3<K|]}t|tywr)r?r))rvvs rrz$ParseResults.dump..)s?B:b,/?rrz]:) rr4rrrsortedrr?r)rdumpanyre)rrrrrrNLrr\rYincrnlr rvv_dumps rrzParseResults.dumps2  <6C //RH773<  <<>@4::<@@E 1JJrN fXtf}%6b2>?!!\2JJtAw'JJs1v& FF%!%1%z  (?$??773<   q\ EAr"l+''!!-!A: "  d6(4&=/1#RtF8DFUVJDWCXY`Xab d6(4&=/1#RtF8DFUVJDWCXY[X\]  wws|rcRtj|jg|i|y)aF Pretty-printer for parsed results as a list, using the `pprint `_ module. Accepts additional positional or keyword args as defined for `pprint.pprint `_ . Example: .. testcode:: 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: .. testoutput:: ['fna', ['a', 'b', ['(', 'fnb', ['c', 'd', '200'], ')'], '100']] N)pprintr)rr'rOs rrzParseResults.pprintAs :  dlln6t6v6rc~|j|jjd|j|jffSr)r:r;rr7r5r#s rr$zParseResults.__getstate__as9 MM ""$    rcd|\|_\|_}}|_t||_d|_yr)r:r;r5rJr7r6)rstater inAccumNamess rr(zParseResults.__setstate__ls.HME E sL$*l+ rc2|j|jfSr)r:r5r#s r__getnewargs__zParseResults.__getnewargs__qs}}djj((rc^tt|t|jzSr)dirrBr@r}r#s r__dir__zParseResults.__dir__ts 4:diik!222rc d}|g}|jD]A\}}t|tr||j||z }-|||g|||z }C| ||g|}|S)z Helper classmethod to construct a :class:`ParseResults` from a ``dict``, preserving the name-value relations as results names. If an optional ``name`` argument is given, a nested :class:`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  **)rN)rNrT)rr?r from_dict)rDrrNrrr\rYs rrzParseResults.from_dictws 5"gKKM ?DAq!W%s}}QQ}//sA3Q{1~>>  ?  se$'C r)NN)r+r,)r+r8)r+r*)r+rr)rr)r+r))r+r))r+r4)rQ)rr8r+r@)r+rL)r+z str | None)rQTTr)5r-r.r/rFr3r0r1r@rGrCr?rr!r^rlrorqrsrwr{r}rdrrrr[rrrrrrrrrrrrrrrrrrr$r(rr classmethodrrTasDictgetNamerrrr)r)(sq1f&*2rNL/2 J  LIE%tE%N0d$:%" %"N>,6 0""8#)#.3% < |!8B#0*< , M   */.`'>R .5nL\7@   )34FFGrr)) __future__rrcollections.abcrrrrrrtypingr utilr r4rr r0rBrKrr)registerrrrrsz#""5\ )2'"x x v %&r