pBFjddlZddlZddlZddlZddlZddlZddlmZmZddlm Z m Z m Z ddl m Z  ddZd Zd Zd ZGd d ZdS)N)chainislice)handlerstagsutil)jsonTFcd|Z|stjdtd| rtjdtd| rtjdtd|pt}|pt ||||||| | | | | |||}|||||| S) aReturn a JSON formatted representation of value, a Python object. :param unpicklable: If set to ``False`` then the output will not contain the information necessary to turn the JSON data back into Python objects, but a simpler JSON stream is produced. It's recommended to set this parameter to ``False`` when your code does not rely on two objects having the same ``id()`` value, and when it is sufficient for those two objects to be equal by ``==``, such as when serializing sklearn instances. If you experience (de)serialization being incorrect when you use numpy, pandas, or sklearn handlers, this should be set to ``False``. If you want the output to not include the dtype for numpy arrays, add:: jsonpickle.register( numpy.generic, UnpicklableNumpyGenericHandler, base=True ) before your pickling code. :param make_refs: If set to False jsonpickle's referencing support is disabled. Objects that are id()-identical won't be preserved across encode()/decode(), but the resulting JSON stream will be conceptually simpler. jsonpickle detects cyclical objects and will break the cycle by calling repr() instead of recursing when make_refs is set False. :param keys: If set to True then jsonpickle will encode non-string dictionary keys instead of coercing them into strings via `repr()`. This is typically what you want if you need to support Integer or objects as dictionary keys. :param max_depth: If set to a non-negative integer then jsonpickle will not recurse deeper than 'max_depth' steps into the object. Anything deeper than 'max_depth' is represented using a Python repr() of the object. :param reset: Custom pickle handlers that use the `Pickler.flatten` method or `jsonpickle.encode` function must call `encode` with `reset=False` in order to retain object references during pickling. This flag is not typically used outside of a custom handler or `__getstate__` implementation. :param backend: If set to an instance of jsonpickle.backend.JSONBackend, jsonpickle will use that backend for deserialization. :param warn: If set to True then jsonpickle will warn when it returns None for an object which it cannot pickle (e.g. file descriptors). :param context: Supply a pre-built Pickler or Unpickler object to the `jsonpickle.encode` and `jsonpickle.decode` machinery instead of creating a new instance. The `context` represents the currently active Pickler and Unpickler objects when custom handlers are invoked by jsonpickle. :param max_iter: If set to a non-negative integer then jsonpickle will consume at most `max_iter` items when pickling iterators. :param use_decimal: If set to True jsonpickle will allow Decimal instances to pass-through, with the assumption that the simplejson backend will be used in `use_decimal` mode. In order to use this mode you will need to configure simplejson:: jsonpickle.set_encoder_options('simplejson', use_decimal=True, sort_keys=True) jsonpickle.set_decoder_options('simplejson', use_decimal=True) jsonpickle.set_preferred_backend('simplejson') NOTE: A side-effect of the above settings is that float values will be converted to Decimal when converting to json. :param numeric_keys: Only use this option if the backend supports integer dict keys natively. This flag tells jsonpickle to leave numeric keys as-is rather than conforming them to json-friendly strings. Using ``keys=True`` is the typical solution for integer keys, so only use this if you have a specific use case where you want to allow the backend to handle serialization of numeric dict keys. :param use_base85: If possible, use base85 to encode binary data. Base85 bloats binary data by 1/4 as opposed to base64, which expands it by 1/3. This argument is ignored on Python 2 because it doesn't support it. :param fail_safe: If set to a function exceptions are ignored when pickling and if a exception happens the function is called and the return value is used as the value for the object that caused the error :param indent: When `indent` is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. ``None`` is the most compact representation. Since the default item separator is ``(', ', ': ')``, the output might include trailing whitespace when ``indent`` is specified. You can use ``separators=(',', ': ')`` to avoid this. This value is passed directly to the active JSON backend library and not used by jsonpickle directly. :param separators: If ``separators`` is an ``(item_separator, dict_separator)`` tuple then it will be used instead of the default ``(', ', ': ')`` separators. ``(',', ':')`` is the most compact JSON representation. This value is passed directly to the active JSON backend library and not used by jsonpickle directly. :param include_properties: Include the names and values of class properties in the generated json. Properties are unpickled properly regardless of this setting, this is meant to be used if processing the json outside of Python. Certain types such as sets will not pickle due to not having a native-json equivalent. Defaults to ``False``. :param handle_readonly: Handle objects with readonly methods, such as Django's SafeString. This basically prevents jsonpickle from raising an exception for such objects. You MUST set ``handle_readonly=True`` for the decoding if you encode with this flag set to ``True``. >>> encode('my string') == '"my string"' True >>> encode(36) == '36' True >>> encode({'foo': True}) == '{"foo": true}' True >>> encode({'foo': [1, 2, [3, 4]]}, max_depth=1) '{"foo": "[1, 2, [3, 4]]"}' Nz-keys will default to True in jsonpickle 5.0.0) stacklevelz@numeric_keys is deprecated, use keys=True (will remove in 5.0.0)zAuse_decimal is deprecated and will be removed in jsonpickle 5.0.0) unpicklable make_refskeysbackend max_depthwarnmax_iter numeric_keys use_decimal use_base85 fail_safeinclude_propertieshandle_readonlyoriginal_object)reset)indent separators)warningsrDeprecationWarningr Picklerencodeflatten)valuer rrrrrrcontextrrrrrrrrrs @C:\PYTHON\_runtimes\venv\Lib\site-packages\jsonpickle/pickler.pyr!r!sD  M?"       MR"       MS"     oG  !-'G >>U++Fz   c|s| o:t||vo)tj| otj| S)z>Detect cyclic structures that would lead to infinite recursion)idr is_primitiveis_enum)objobjs max_reachedrs r% _in_cycler.sM  ;Y:2c77d? "!#&& & " S!! !r&cBtjtj|iS)zxReturn a typeref dictionary >>> _mktyperef(AssertionError) == {'py/type': 'builtins.AssertionError'} True )rTYPErimportable_name)r+s r% _mktyperefr2s It+C00 11r&c6t|tr|fS|S)z0Converts __slots__ = 'a' into __slots__ = ('a',)) isinstancestr)strings r%_wrap_string_slotr7s!&#y Mr&ceZdZ d$dZdZdZdZdZd Zd Z d Z d Z d Z d%dZ dZdZdZdZdZdZdZdZdZdZd&dZdZdZdZdZdZdZd'd!Zd"Z d#Z!dS)(r TNFc||_||_|pt|_||_||_||_| |_d|_||_ i|_ g|_ ||_ | |_ i|_| |_|jr#t j|_t&j|_n"t j|_t&j|_| |_| |_||_dSN)r rr rrrrr_depth _max_depth_objs_seen _max_iter _use_decimal _flattenedrrB85 _bytes_tagr b85encode_bytes_encoderB64 b64encoderr_original_object)selfr rrrrrrrrrrrrrs r%__init__zPickler.__init__s"'"$   ($ #  !'. ? 1"hDO"&.D  "hDO"&.D #"4 /r&ct|jdiD]\}}|ddrdSdS)N_encoder_options sort_keysFT)getattrrvaluesget)rJ_optionss r%_determine_sort_keyszPickler._determine_sort_keyssY!$,0BBGGNNPP  JAw{{;.. tt ur&ct|dr|jrtdt|drQ tt |j|_n#ttf$rYnwxYw|S)N __slots__zObjects with __slots__ cannot have their keys reliably sorted by jsonpickle! Please sort the keys in the __slots__ definition instead.__dict__)hasattrr TypeErrordictsortedrWitemsAttributeErrorrJr+s r% _sort_attrszPickler._sort_attrss 3 $ $   X  S* % %  #F3<+=+=+?+?$@$@AA ~.     s8A11BBc>i|_d|_g|_i|_dSr:)r>r<r?rBrJs r%rz Pickler.reset*s"   r&c&|xjdz c_dS)z&Steps down one level in the namespace.rN)r<ras r%_pushz Pickler._push0s q r&cd|xjdzc_|jdkr||S)zzStep up one level in the namespace and return the value. If we're at the root, reset the pickler's state. rr;)r<r)rJr#s r%_popz Pickler._pop4s3 q ;"   JJLLL r&cvt|}||jv}|rt|j}||j|<|S)z Log a reference to an in-memory object. Return True if this object is new and was assigned a new ID. Otherwise return False. )r(r>len)rJr+objidis_newnew_ids r%_log_refzPickler._log_ref=sA 3dj(  '__F &DJu  r&cT||}|j p|j }|p|S)z~ Log a reference to an in-memory object, and return if that object should be considered newly logged. )rkr r)rJr+ri pretend_news r%_mkrefzPickler._mkrefJs5 s##**@$..@ $f$r&chtj|jt |iS)z/Return a "py/id" entry for the specified object)rIDr>rQr(r^s r%_getrefzPickler._getrefTs#30011r&c|jr|jr||}nX |jt |}n<#t $r/||x}|jt |<YnwxYw|S)z>Flatten an object and its guts into a json-safe representation)r r _flatten_implrBr(KeyError)rJr+results r%_flattenzPickler._flattenXs   L L'',,FF LC1 L L L484F4Fs4K4KKC111 L sA6A:9A:c|r||r||}||S)aTakes an object and returns a JSON-safe representation of it. Simply returns any of the basic builtin datatypes >>> p = Pickler() >>> p.flatten('hello world') == 'hello world' True >>> p.flatten(49) 49 >>> p.flatten(350.0) 350.0 >>> p.flatten(True) True >>> p.flatten(False) False >>> r = p.flatten(None) >>> r is None True >>> p.flatten(False) False >>> p.flatten([1, 2, 3, 4]) [1, 2, 3, 4] >>> p.flatten((1,2,))[tags.TUPLE] [1, 2] >>> p.flatten({'key': 'value'}) == {'key': 'value'} True )rrTr_rv)rJr+rs r%r"zPickler.flattencsR8   JJLLL  $ $ & & (""3''C}}S!!!r&c:|j||iSN)rDrFr^s r%_flatten_bytestringzPickler._flatten_bytestrings!4!4S!9!9::r&ct|tur||St|ttt t tdfvs!|jrt|tj r|S| | | |Sry)typebytesrzr5boolintfloatrAr4decimalDecimalrcre _flatten_objr^s r%rszPickler._flatten_impls 99  ++C00 0 99dCT ; ; ;   <",S'/"B"B <J yy**3//000r&c"|j|jkSry)r<r=ras r% _max_reachedzPickler._max_reacheds{do--r&cJ|jrd|z}tj|dSdS)Nz/jsonpickle cannot pickle %r: replaced with None)rr)rJr+msgs r%_pickle_warningzPickler._pickle_warnings6 9 CcIC M#       r&c|j||} t||j||j}|rt }n||}|||dS||S#ttf$r}|d}~wt$r(}|j || |cYd}~Sd}~wwxYwry) r?appendrr.r>rrepr_get_flattenerrKeyboardInterrupt SystemExit Exceptionr)rJr+r-in_cycle flatten_funces r%rzPickler._flatten_objs #''))  ) dj+t~NNH 8# #22377 #$$S)))t<$$ $!:.   G ) ) )~%~~a((((((((  )s0AB BC B"" C/C CCc fd|DS)Nc:g|]}|Srv.0vrJs r% z)Pickler._list_recurse..s%...Q a  ...r&rr^s` r% _list_recursezPickler._list_recurses....#....r&cZ|jr!tjtj|i}nd}|Sry)r rFUNCTIONrr1)rJr+datas r%_flatten_functionzPickler._flatten_functions0   M4#7#<#<=DDD r&cb||}|jr||tj<n|}|Sry)rvr rSTATE)rJr+rstates r% _getstatezPickler._getstates7 c""   $D  D r&ctj||s|S|jrB|dtj|jDvrtj|j||r|S|d}|jrt|ttfrnEt|ts0 t|}n#t$rt|}YnwxYw||||<|S)z7Flatten a key/value pair into the passed-in dictionary.ch|]\}}|Srr)rattrvals r% z2Pickler._flatten_key_value_pair..sVVVytSdVVVr&Nnull)r is_picklablerinspect getmembersrI is_readonlyrr4rrr5rrrvrJkrrs r%_flatten_key_value_pairzPickler._flatten_key_value_pairs  A&& K   VVG,>t?T,U,UVVVVV !61==WK 9A   AU|!.valid_propertys*tt,,,I1\1I Ir&c6g|]}| |dS)rr)rrrs r%rz/Pickler._flatten_properties..s<   ~~a?P?P aD   r&) set itertoolsr from_iterablerrrrOr is_not_classrvrPROPERTY) rJr+rallslots propertiesproperties_dictp_namep_valrrs @@r%_flatten_propertieszPickler._flatten_propertiess  H9?88BBCC  J J J J J    !,S];;     ? ?FC((E '' ?*/''*.--*>*>''-T] r&c$d|jD}|jr||||}||t ||s0dt |D}|||||S)zAReturn a json-friendly dict for new-style objects with __slots__.c bg|],}tt|dt-S)rV)r7rOtuple)rclss r%rz8Pickler._flatten_newstyle_with_slots..s@    gc;@@ A A   r&cfg|].}|d|d,|/S)r)rendswith)rrs r%rz8Pickler._flatten_newstyle_with_slots.."sN1<<+=+=FGjjQUFVFVr&)rmrorrrrdir)rJr+rrrs r%_flatten_newstyle_with_slotsz$Pickler._flatten_newstyle_with_slotss  }((**     " A++Cx@@D&&sE8, i}t|d}t|d}| ot|d}tj|d}tj|d}tj|d}tj|\} } t t |dd} tt |d o)t |jt td d u} |r|j } nt |} tj | }tj | tj |}|Nj r||tj<|||}|||Sd }jr||}j r%| r(| s& |}n9#t*$rYn-wxYw| r' |d }n#t*$rYnwxYw|rt/|t0r t3|d }t6jt;|}|D](}t ||}|cSnL#t>$rYn?wxYw|r8tA|}d tC|z }|r |d g|zz }t |ddddkrtj"|d<|\}}}}}|r'| r%t|dst/|tFr|drtI|d|d<|drtI|d|d<tAtKj|}tC|dz }|d kr|||dz}|d kr|||d |dz|tj&<|S|rt/|tNj(sj r||tj<|r-fd|)D|tj*<|r6|s4|+|tj,<|r4|-|tj.<| rT |}|r/||Sn&#t*$r|Yd SwxYwt/|tNj(rAj r)d0|j1|tj2<nt1|}|Stj3|r4||| |Stj5|r6||Stj7|rDtAtKjtq|j9|tj:<|S|rXtj5|r6||St |dd 4|j;|| S|r<||S|r|S|d S)z?Recursively flatten an instance and return a json-friendly dictrrWrV__getnewargs____getnewargs_ex____getinitargs___jsonpickle_excluder __getstate__Nr .rr __newobj__ __setstate__rc:g|]}|Srr)rargrJs r%rz1Pickler._flatten_obj_instance..s2(((+.DMM#&&(((r&z {name}/{name})nameexcluderR)=rXr has_method has_reducerrOr|robjectrr1rrQr rOBJECTr"rrr __reduce__rY __reduce_ex__r4r5itersplitsysmodulesnextrvrtlistrgNEWOBJrZrmapREDUCEtypes ModuleTyper NEWARGSEXrNEWARGSrINITARGSrformatrMODULEis_dictionary_subclass_flatten_dict_objis_sequence_subclass_flatten_sequence_obj is_iteratorrr@ITERATORrWr)rJr+r has_classhas_dict has_slotshas_getnewargshas_getnewargs_exhas_getinitargsr has_reduce_exrhas_own_getstater class_namehandlerru reduce_valvarpathcurmodmodname rv_as_list insufficiencyfargsr listitems dictitems reduce_args last_indexs` r%_flatten_obj_instancezPickler._flatten_obj_instance)s]C-- 3 ++ L>WS+%>%> .>?? OC1DEE/#/@AA$(OC$8$8! Mgc#8"==>>#499n==D$ C C gfndCCCD  -CCs))C)#.. ,sHL$<$<==   /$.T[!WT]]**355F~$$S)))M  " 7++C66D  E  - !$!1!1JJ D  !$!2!21!5!5JJ D  / jS99/  ":#3#3C#8#899G![g7F#*55!(!9!9#}}V444445 D! "*-- !C OO 3  94&="88J:a=*b99\II$(KJqM7A44 9 ( $C88 'sD11  "!}=(-jm(<(< 1 !!}=(-jm(<(< 1 "&s4=*'E'E"F"FK!$[!1!1A!5J$//k*.E.M"a %//k*.E.M(34Dj1n4D(ED%K  KZU-=>> K /$.T[!  ((((252G2G2I2I(((T^$ I&7 I%)]]33E3E3G3G%H%HT\" K&*mmC4G4G4I4I&J&JT]#  7 7((**7>>%6667    $$S)))tt   c5+ , ,  $3$:$: $:$M$MT[!!3xxK  &s + +   " "3g " > > >K  $S ) ) 9--c488 8  C  "&s4=&dn:U:U'V'V"W"WD K  O(-- =11#t<<< Cd # # #))#,g)NN N  @44S$?? ?  K S!!!tsIG G$#G$*H H  H (A+J J$#J$4S!!TTc@|jr?||r||S||S|}t ||j|d}|rdS||||S)z.Reference an existing object or flatten if newFN)r rnrrqrr.r>)rJr+r-rs r%_ref_obj_instancezPickler._ref_obj_instances   3{{3 711#666<<$$ $++--K dj+uEEH t KK   --c22 2r&c Ztjt|dd||j|jzS)NFT)rrr$rr)rJSON_KEYr!rr)rJrs r% _escape_keyzPickler._escape_keys8}v Ln      r&ctj||s|S|jrBt|ts-||}||||<|S)z'Flatten only non-string key/value pairs)rrrr4r5rrvrs r%"_flatten_non_string_key_value_pairz*Pickler._flatten_non_string_key_value_pairsd A&& K 9 'Z3// '  ##AmmA&&DG r&ctj||s|S|jrLt|ts|S|t jr||}nm|d}|j rt|ttfrnEt|ts0 t|}n#t$rt |}YnwxYw||||<|S)z$Flatten string key/value pairs only.Nr)rrrr4r5rrrrrrrrrrvrs r%_flatten_string_key_value_pairz&Pickler._flatten_string_key_value_pairs A&& K 9 a%% ( dm,, ($$Q''y  ZC<%@%@ 3'' QAA AAAA--""Q s)B99CCrc||}|jra|j}tj||D]\}}|||||j}tj||D]\}}||||n0|j}tj||D]\}}||||t|drt|j r|j }tj |rt|}nZ| |r0| tj|}n||}||d<t|drn|jrg||jkr\| |jr%i} ||j| || |d<n||j|d<|S)z8Recursively call flatten() and return json-friendly dictNrdefault_factoryrW)rrr rr\rrrXcallabler"is_typer2rnrr CloneFactoryrqr rWr) rJr+rrr"rrfactoryr# dict_datas r%rzPickler._flatten_dict_objs$ <==??D 9 $9G 3888 $ $11d####=G 3888 $ $11d#### $2G 3888 $ $11d#### 3) * * ,x8K/L/L ,)G|G$$ 2"7++;;w''2!66x7LWWYY7W7WXXEE!LL11E&+D" # 3 # # >(8 >SCL=P=P{{3<(( > &&s|Y&PPP#,Z  #'<< #=#=Z  r&ct|ttfvr@|r$t|turjnjSjSt|ttfvrj sjSfdStj |rj Stj |rjStj|rt S|dS)Nc|t|tur tjn tjfd|DiS)Nc:g|]}|Srrrs r%rz...as%>>>Q a 0 0>>>r&)r|rrTUPLESET)r+rJs r%z(Pickler._get_flattener..^s@99%% X>>>>#>>> r&)r|rrZrnrrrqrrr ris_module_functionr is_objectrr$r2rr^s` r%rzPickler._get_flattenerQs  99t $ ${{3 $*.s))t*;*;D&&AW|##YY5#, & &# *))   $S ) ) ) ) ^C  ) ) \#     S!!!tr&ct|dr|j|fd|D}jr||tj<n|S|S)z4Return a json-friendly dict for a sequence subclass.rWc:g|]}|Srrrs r%rz1Pickler._flatten_sequence_obj..us%///aq!!///r&)rXrrWr rSEQ)rJr+rr#s` r%rzPickler._flatten_sequence_objqsh 3 # # 7  " "3< 6 6 6////3///   "DNNL r&)TTNNFFNFFFNFFN)Try)Nr)"r __module__ __qualname__rKrTr_rrcrerkrnrqrvr"rzrsrrrrrrrrrrrrrrr rrrrr&r%r r s-   40404040l(    %%%222    " " " "D;;;111"... )))6///6 8&pppd333*   04444l@     r&r )TTFNTNFNNFFFNNNFF)rrrrrrrrrrrrrr r!r.r2r7r rr&r%r5s? ########""""""""""        %hhhhV222b b b b b b b b b b r&