U
    NvfB                     @   s@  d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlmZ ddlmZmZ ddlmZmZ ddlmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 ej1dkr"dKd	d
Z2dLddZ3ndMdd
Z2dNddZ3ej4ej5 Z4Z5dd Z6dd Z7dd Z8dd Z9dd Z:dd Z;dd Z<dd Z=dd  Z>d!d" Z?d#d$ Z@d%d& ZAd'd( ZBd)d* ZCd+d, ZDd-d. ZEd/d0 ZFd1d2 ZGd3d4 ZHd5d6 ZId7d8 ZJd9d: ZKd;d< ZLd=d> ZMd?d@ ZNdAdB ZOdCdD ZPdEdF ZQdGdH ZRG dIdJ dJeZSdS )Oa  
New, fast version of the CloudPickler.

This new CloudPickler class can now extend the fast C Pickler instead of the
previous Python implementation of the Pickler class. Because this functionality
is only available for Python versions 3.8+, a lot of backward-compatibility
code is also removed.

Note that the C Pickler subclassing API is CPython-specific. Therefore, some
guards present in cloudpickle.py that were written to handle PyPy specificities
are not present in cloudpickle_fast.py
    N)Enum)ChainMapOrderedDict   )picklePickler)_extract_code_globals_BUILTIN_TYPE_NAMESDEFAULT_PROTOCOL_find_imported_submodules_get_cell_contents_should_pickle_by_reference_builtin_type_get_or_create_tracker_id_make_skeleton_class_make_skeleton_enum_extract_class_dictdynamic_subimport	subimport_typevar_reduce
_get_bases
_make_cell_make_empty_cellCellType_is_parametrized_type_hintPYPYcell_set"parametrized_type_hint_getinitargs_create_parametrized_type_hintbuiltin_code_type_make_dict_keys_make_dict_values_make_dict_items_make_function   c                 C   s   t |||d|  dS )  Serialize obj as bytes streamed into file

        protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
        pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
        speed between processes running the same Python version.

        Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
        compatibility with older versions of Python.
        protocolbuffer_callbackNCloudPicklerdump)objfiler'   r(    r.   Q/tmp/pip-unpacked-wheel-dylwa62s/joblib/externals/cloudpickle/cloudpickle_fast.pyr+   -   s    
  r+   c              
   C   s@   t  .}t|||d}||  | W  5 Q R  S Q R X dS )  Serialize obj as a string of bytes allocated in memory

        protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
        pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
        speed between processes running the same Python version.

        Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
        compatibility with older versions of Python.
        r&   NioBytesIOr*   r+   getvalue)r,   r'   r(   r-   cpr.   r.   r/   dumps;   s    

  
r6   c                 C   s   t ||d|  dS )r%   r'   Nr)   )r,   r-   r'   r.   r.   r/   r+   N   s    
c              
   C   s>   t  ,}t||d}||  | W  5 Q R  S Q R X dS )r0   r7   Nr1   )r,   r'   r-   r5   r.   r.   r/   r6   Z   s    


c                 C   sV   i }d| j kr| j|d< | j dd }t|tr8||d< t| | jt| |t| d fS )N	__slots____dict__)	r9   r8   get
isinstancepropertytype__name__r   r   )r,   Ztype_kwargsr9   r.   r.   r/   _class_getnewargsp   s    


 r?   c                 C   s,   dd | D }| j | j| j|| jt| d fS )Nc                 S   s   i | ]}|j |jqS r.   namevalue.0er.   r.   r/   
<dictcomp>~   s      z$_enum_getnewargs.<locals>.<dictcomp>)	__bases__r>   __qualname__
__module__r   )r,   membersr.   r.   r/   _enum_getnewargs}   s      rK   c                 C   s   | S Nr.   )retvalr.   r.   r/   _file_reconstructor   s    rN   c              	      s    j  j j j j j j jd}t j	} fdd|D } jd k	r\t
tt jnd}t j	t| ||d< ||d<  j}||fS )N)r>   rH   __annotations____kwdefaults____defaults__rI   __doc____closure__c                    s"   i | ]}| j kr| j | qS r.   )__globals__)rD   kfuncr.   r/   rF      s       z&_function_getstate.<locals>.<dictcomp>r.   _cloudpickle_submodulesrT   )r>   rH   rO   rP   rQ   rI   rR   rS   r   __code__listmapr   r   	itertoolschainvaluesr9   )rW   	slotstateZf_globals_ref	f_globalsZclosure_valuesstater.   rV   r/   _function_getstate   s,    
	 rb   c                 C   s   t | }|dd  tt| tjr|dd  |dd  |dd  |dd }|d kr|dd  t| \}}}}dd |D |d< nd	d |D |d< d
|krt| jt	r|| j n| jD ]}||d  q|dd  |i fS )N__weakref__
_abc_cache_abc_negative_cache_abc_negative_cache_version_abc_registry	_abc_implc                 S   s   g | ]
}| qS r.   r.   )rD   Zsubclass_weakrefr.   r.   r/   
<listcomp>   s   z#_class_getstate.<locals>.<listcomp>c                 S   s   g | ]}|qS r.   r.   )rD   type_r.   r.   r/   ri      s     r8   r9   )
r   pop
issubclassr=   abcABCMeta	_get_dumpr;   r8   str)r,   clsdictregistry_rU   r.   r.   r/   _class_getstate   s*    
rt   c                 C   sL   t | \}}dd | D }dD ]}||d  q|D ]}|| q4||fS )Nc                 S   s   i | ]}|j |jqS r.   r@   rC   r.   r.   r/   rF      s      z"_enum_getstate.<locals>.<dictcomp>)_generate_next_value__member_names__member_map__member_type__value2member_map_)rt   rk   )r,   rq   r_   rJ   attrnamememberr.   r.   r/   _enum_getstate   s    r|   c                 C   s  t | drZ| j| j| j| j| j| j| j| j| j	| j
| j| j| j| j| j| j| j| jf}nHt | dr| j| j| j| j| j| j| j| j| j	| j
| j| j| j| j| j| jf}nt | dr| j| j| j| j| j| j| j| j| j| j| j
| j| j| j| j| j| j| j| j| j| jf}nt | drb| j| j| j| j| j| j| j| j| j	| j
| j| j| j| j| j| jf}n@| j| j| j| j| j| j| j| j	| j
| j| j| j| j| j| jf}tj|fS )zcodeobject reducerco_exceptiontableco_linetableco_nmetaco_posonlyargcount)hasattrco_argcountr   co_kwonlyargcount
co_nlocalsco_stacksizeco_flagsco_code	co_constsco_namesco_varnamesco_filenameco_nameZco_qualnameco_firstlinenor~   r}   co_freevarsco_cellvarsZco_framesizeZco_ndefaultargsr   	co_lnotabZco_exc_handlersZco_jump_tableZco_free2regZco_cell2regtypesCodeType)r,   argsr.   r.   r/   _code_reduce   s    
            
                       
                    r   c                 C   s8   z
| j  W n tk
r&   tdf Y S X t| j ffS dS )z?Cell (containing values of a function's free variables) reducerr.   N)cell_contents
ValueErrorr   r   r,   r.   r.   r/   _cell_reduce3  s
    
r   c                 C   s   | j }t| |ffS rL   )__func__r=   )r,   Z	orig_funcr.   r.   r/   _classmethod_reduce=  s    r   c              
   C   sF  ddl }t| drt| ds&td| tjkr<ttdffS | tjkrRttdffS | tjkrftd| j	rvtd	t| d
r| 
 rtdd| jkrd| jkrtd| j | j}| }z(|  }| d |  }| | W n4 tk
r  } ztd| |W 5 d}~X Y nX || || ||_t|ffS )zSave a filer   NrA   modez5Cannot pickle files that do not map to an actual filestdoutstderrzCannot pickle standard inputzCannot pickle closed filesisattyz+Cannot pickle files that map to tty objectsr+z7Cannot pickle files that are not opened for reading: %sz*Cannot pickle file %s as it cannot be read)r2   r   r   PicklingErrorsysr   getattrr   stdinclosedr   r   rA   StringIOtellseekreadIOErrorwriterN   )r,   r2   rA   rM   ZcurloccontentsrE   r.   r.   r/   _file_reduceB  sP    







r   c                 C   s   t | j| jffS rL   )r   __objclass__r>   r   r.   r.   r/   _getset_descriptor_reduceq  s    r   c                 C   s   t jt| ffS rL   )r   MappingProxyTypedictr   r.   r.   r/   _mappingproxy_reduceu  s    r   c                 C   s   t |  ffS rL   )bytestobytesr   r.   r.   r/   _memoryview_reducey  s    r   c                 C   s<   t | rt| jffS | j }|dd  t| j|ffS d S )N__builtins__)r   r   r>   r9   copyrk   r   )r,   ra   r.   r.   r/   _module_reduce}  s
    
r   c                 C   s   t j| j| jffS rL   )r   
MethodTyper   __self__r   r.   r.   r/   _method_reduce  s    r   c                 C   s   t j| jffS rL   )logging	getLoggerrA   r   r.   r.   r/   _logger_reduce  s    r   c                 C   s
   t jdfS )Nr.   )r   r   r   r.   r.   r/   _root_logger_reduce  s    r   c                 C   s   t | j| j| j| jffS rL   )r<   fgetfsetfdelrR   r   r.   r.   r/   _property_reduce  s    r   c                 C   s   t jt| ffS rL   )weakrefWeakSetrZ   r   r.   r.   r/   _weakset_reduce  s    r   c                 C   sF   t dk	r*t| t r*tt| t| ddtfS tt| t| ddtfS dS )z
    Save a class that can't be stored as module global.

    This method is used to serialize classes that are defined inside
    functions, or that otherwise can't be serialized as attribute lookups
    from global modules.
    N)	r   rl   r   rK   r|   _class_setstater   r?   rt   r   r.   r.   r/   _dynamic_class_reduce  s            r   c                 C   sj   | t dkrt dfS | t tkr*t tffS | t tkr@t tffS | tkrVtt|  ffS t| sft| S tS )zCSelect the reducer depending on the dynamic nature of the class objNrL   )r=   EllipsisNotImplementedr	   r   r   r   r   r.   r.   r/   _class_reduce  s    

r   c                 C   s   t t| ffS rL   r    rZ   r   r.   r.   r/   _dict_keys_reduce  s    r   c                 C   s   t t| ffS rL   r!   rZ   r   r.   r.   r/   _dict_values_reduce  s    r   c                 C   s   t t| ffS rL   r"   r   r   r.   r.   r/   _dict_items_reduce  s    r   c                 C   s   t t| dffS NTr   r   r.   r.   r/   _odict_keys_reduce  s    r   c                 C   s   t t| dffS r   r   r   r.   r.   r/   _odict_values_reduce  s    r   c                 C   s   t t| dffS r   r   r   r.   r.   r/   _odict_items_reduce  s    r   c           
   	   C   s   |\}}| j | |d}|d}|d | j| t| jd< |dk	rt|D ]<\}}z
|j}W n tk
r   Y qXY nX t| j	| | qX|
 D ]\}}	t| ||	 qdS )a  Update the state of a dynamic function.

    As __closure__ and __globals__ are readonly attributes of a function, we
    cannot rely on the native setstate routine of pickle.load_build, that calls
    setattr on items of the slotstate. Instead, we have to modify them inplace.
    rT   rS   rX   r   N)r9   updaterk   rT   r   	enumerater   r   r   rS   itemssetattr)
r,   ra   r_   Zobj_globalsZobj_closureicellrB   rU   vr.   r.   r/   _function_setstate  s     





r   c                 C   sX   |\}}d }|  D ]"\}}|dkr*|}qt| || q|d k	rT|D ]}| | qD| S )Nrh   )r   r   register)r,   ra   r_   rr   rz   attrsubclassr.   r.   r/   r     s    r   c                   @   s  e Zd Zi Zeee< eeej< e	ee
j< eee
j< eee< eee< eee< eee< eeej< eeej< eeej< eeej< eeej< e ee!j"< e#ee$j%< e&ee'j(< e)ee'j*< e+ee'j,< e-ee.e/ 0 < e1ee.e/ 2 < e3ee.e/ 4 < eee5j6< eee5j7< eee5j8< eee5j9< e:ee;j<Z<dd Z=dd Z>dd Z?dd Z@eAjBd	krXdddZCn
dddZCeAjBd	kreDse<ZEdd ZFnHeGjEH ZEdddZId
eJjKfddZLeLeEe.< dddZMdd ZNeMeEejO< d
S )r*   c                 C   s"   |  |}t|}t||ddtfS )z>Reduce a function that is not pickleable via attribute lookup.N)_function_getnewargsrb   r#   r   )selfrW   Znewargsra   r.   r.   r/   _dynamic_function_reduce=  s
    

z%CloudPickler._dynamic_function_reducec                 C   s   t |rtS | |S dS )a  Reducer for function objects.

        If obj is a top-level attribute of a file-backed module, this
        reducer returns NotImplemented, making the CloudPickler fallback to
        traditional _pickle.Pickler routines to save obj. Otherwise, it reduces
        obj using a custom cloudpickle reducer designed specifically to handle
        dynamic functions.

        As opposed to cloudpickle.py, There no special handling for builtin
        pypy functions because cloudpickle_fast is CPython-specific.
        N)r   r   r   )r   r,   r.   r.   r/   _function_reduceD  s    zCloudPickler._function_reducec                 C   s~   |j }| jt|ji }|i krDdD ]}||jkr&|j| ||< q&|jd krTd }ntdd tt|j	D }||d d |fS )N)__package__r>   __path____file__c                 s   s   | ]}t  V  qd S rL   )r   )rD   rs   r.   r.   r/   	<genexpr>q  s    z4CloudPickler._function_getnewargs.<locals>.<genexpr>)
rY   globals_ref
setdefaultidrT   rS   tuplerangelenr   )r   rW   codebase_globalsrU   closurer.   r.   r/   r   U  s    

z!CloudPickler._function_getnewargsc              
   C   sX   zt | |W S  tk
rR } z&d|jd kr@d}t||n W 5 d }~X Y nX d S )N	recursionr   z?Could not pickle object as excessively deep recursion required.)r   r+   RuntimeErrorr   r   r   )r   r,   rE   msgr.   r.   r/   r+   v  s    zCloudPickler.dumpr$   Nc                 C   s2   |d krt }tj| |||d i | _t|| _d S )Nr&   )r
   r   __init__r   intproto)r   r-   r'   r(   r.   r.   r/   r     s       zCloudPickler.__init__c                 C   s4   |d krt }tj| ||d i | _t| ds0td S )Nr7   r   )r
   r   r   r   r   AssertionError)r   r-   r'   r.   r.   r/   r     s
    c                 C   s   t jdd dk r&t|r&tt|fS t|}zt|t}W n tk
rT   d}Y nX |rbt|S t	|t
jrx| |S tS dS )a*  Type-agnostic reducing callback for function and classes.

            For performance reasons, subclasses of the C _pickle.Pickler class
            cannot register custom reducers for functions and classes in the
            dispatch_table. Reducer for such types must instead implemented in
            the special reducer_override method.

            Note that method will be called for any object except a few
            builtin-types (int, lists, dicts etc.), which differs from reducers
            in the Pickler's dispatch_table, each of them being invoked for
            objects of a specific type only.

            This property comes in handy for classes: although most classes are
            instances of the ``type`` metaclass, some of them can be instances
            of other custom metaclasses (such as enum.EnumMeta for example). In
            particular, the metaclass will likely not be known in advance, and
            thus cannot be special-cased using an entry in the dispatch_table.
            reducer_override, among other things, allows us to register a
            reducer that will be called for any class, independently of its
            type.


            Notes:

            * reducer_override has the priority over dispatch_table-registered
            reducers.
            * reducer_override can be used to fix other limitations of
              cloudpickle for other types that suffered from type-specific
              reducers, such as Exceptions. See
              https://github.com/cloudpipe/cloudpickle/issues/248
            N         F)r   version_infor   r   r   r=   rl   	TypeErrorr   r;   r   FunctionTyper   r   )r   r,   tZis_anyclassr.   r.   r/   reducer_override  s     

zCloudPickler.reducer_overridec           
      C   s\   | j }| j}	| j||d |||d || || || |	tj |	tj |	tj d S )N)ra   	listitems	dictitemsr,   )saver   save_reducer   TUPLE2REDUCEPOP)
r   rW   r   ra   r  r  state_setterr,   r  r   r.   r.   r/   _save_reduce_pickle5  s         

z!CloudPickler._save_reduce_pickle5c                 C   s   |t dkr| jt d|dS |t tkr:| jt tf|dS |t tkrX| jt tf|dS |tkrv| jtt| f|dS tjdd dk rt|r| jt	t
||d nL|dk	rtj| ||d n2t||ds| jt|d|i ntj| ||d dS )z
            Save a "global".

            The name of this method is somewhat misleading: all types get
            dispatched here.
            NrL   r   r   r   rA   r,   )r=   r  r   r   r	   r   r   r   r   r   r   r   save_globalr   r
  r   )r   r,   rA   packr.   r.   r/   r    s.      zCloudPickler.save_globalc                 C   sP   t ||drtj| ||dS tr6t|jtr6| |S | j| 	|d|iS dS )z Registered with the dispatch to handle all function types.

            Determines what kind of function obj is (e.g. lambda, defined at
            interactive prompt, etc) and handles the pickling appropriately.
            r  r,   N)
r   r   r  r   r;   rY   r   save_pypy_builtin_funcr
  r   )r   r,   rA   r.   r.   r/   save_function'  s    
zCloudPickler.save_functionc                 C   s4   t j|ji |j|j|jf|jf}| j|d|i dS )a
  Save pypy equivalent of builtin functions.
            PyPy does not have the concept of builtin-functions. Instead,
            builtin-functions are simple function instances, but with a
            builtin-code attribute.
            Most of the time, builtin functions should be pickled by attribute.
            But PyPy has flaky support for __qualname__, so some builtin
            functions such as float.__new__ will be classified as dynamic. For
            this reason only, we created this special routine. Because
            builtin-functions are not expected to have closure or globals,
            there is no additional hack (compared the one already implemented
            in pickle) to protect ourselves from reference cycles. A simple
            (reconstructor, newargs, obj.__dict__) tuple is save_reduced.  Note
            also that PyPy improved their support for __qualname__ in v3.6, so
            this routing should be removed when cloudpickle supports only PyPy
            3.6 and later.
            r,   N)r   r   rY   r>   rQ   rS   r9   r  )r   r,   rvr.   r.   r/   r  6  s     z#CloudPickler.save_pypy_builtin_func)NN)N)NNNNN)N)Pr>   rI   rH   Z_dispatch_tabler   classmethodr   r2   TextIOWrapperr   r   Loggerr   
RootLoggerr   
memoryviewr   r<   staticmethodr   r   r   r   r   r   GetSetDescriptorTyper   
ModuleTyper   r   r   r   r   r   r   r   typingTypeVarr   _collections_abc	dict_keysr   dict_valuesr   
dict_itemsr   r=   r   keysr   r^   r   r   rm   abstractmethodabstractclassmethodabstractstaticmethodabstractpropertyr   copyregdispatch_tabler   r   r   r+   r   HIGHEST_PROTOCOLr   r   dispatchr  r   r   r
  structr  r  r  r  r   r.   r.   r.   r/   r*     s`   
















!


9
      
"
r*   )NN)NN)N)N)TrR   r  rm   r$  r2   r\   r   r   r(  r   r   r  enumr   collectionsr   r   compatr   r   Zcloudpickler   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r&  r+   r6   loadloadsr?   rK   rN   rb   rt   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r*   r.   r.   r.   r/   <module>   sf   x


'(>
/
"