3
AAd]5Š  ã               @   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mZmZ ddl	Z	ddl
mZ ddlmZ ejd Zee	jg ƒƒZdd„ Zd	d
„ ZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ deƒZG dd„ dƒZ G dd„ dƒZ!G dd„ dƒZ"dd „ Z#d!d"„ Z$d#d$„ Z%d%d&„ Z&d'd(„ Z'd)d*„ Z(d+d,„ Z)d3d-d.„Z*e"j+j e*_ d/d0„ Z,d1d2„ Z-dS )4aw  This module provides code that allows one to pickle the state of a
Python object to a dictionary.

The motivation for this is simple.  The standard Python
pickler/unpickler is best used to pickle simple objects and does not
work too well for complex code.  Specifically, there are two major
problems (1) the pickle file format is not easy to edit with a text
editor and (2) when a pickle is unpickled, it creates all the
necessary objects and sets the state of these objects.

Issue (2) might not appear to be a problem.  However, often, the
determination of the entire 'state' of an application requires the
knowledge of the state of many objects that are not really in the
users concern.  The user would ideally like to pickle just what he
thinks is relevant.  Now, given that the user is not going to save the
entire state of the application, the use of pickle is insufficient
since the state is no longer completely known (or worth knowing).  The
default `Unpickler` recreates the objects and the typical
implementation of `__setstate__` is usually to simply update the
object's `__dict__` attribute.  This is inadequate because the pickled
information is taken out of the real context when it was saved.

The `StatePickler` basically pickles the 'state' of an object into a
large dictionary.  This pickled data may be easily unpickled and
modified on the interpreter or edited with a text editor
(`pprint.saferepr` is a friend).  The second problem is also
eliminated.  When this state is unpickled using `StateUnpickler`, what
you get is a special dictionary (a `State` instance).  This allows one
to navigate the state just like the original object.  Its up to the
user to create any new objects and set their states using this
information.  This allows for a lot of flexibility while allowing one
to save and set the state of (almost) any Python object.

The `StateSetter` class helps set the state of a known instance.  When
setting the state of an instance it checks to see if there is a
`__set_pure_state__` method that in turn calls `StateSetter.set`
appropriately.

Additionally, there is support for versioning.  The class' version is
obtain from the `__version__` class attribute.  This version along
with the versions of the bases of a class is embedded into the
metadata of the state and stored.  By using `version_registry.py` a
user may register a handler for a particular class and module.  When
the state of an object is set using `StateSetter.set_state`, then
these handlers are called in reverse order of their MRO.  This gives
the handler an opportunity to upgrade the state depending on its
version.  Builtin classes are not scanned for versions.  If a class
has no version, then by default it is assumed to be -1.


Example::

  >>> class A:
  ...    def __init__(self):
  ...        self.a = 'a'
  ... 
  >>> a = A()
  >>> a.a = 100
  >>> from . import state_pickler
  >>> s = state_pickler.dumps(a)               # Dump the state of `a`.
  >>> state = state_pickler.loads_state(s)     # Get the state back.
  >>> b = state_pickler.create_instance(state) # Create the object.
  >>> state_pickler.set_state(b, state)        # Set the object's state.
  >>> assert b.a == 100


Features
--------

 - The output is a plain old dictionary so is easy to parse, edit etc.
 - Handles references to avoid duplication.
 - Gzips Numeric arrays when dumping them.
 - Support for versioning.


Caveats
-------

 - Does not pickle a whole bunch of stuff including code objects and
   functions.
 - The output is a pure dictionary and does not contain instances.  So
   using this *as it is* in `__setstate__` will not work.  Instead
   define a `__set_pure_state__` and use the `StateSetter` class or
   the `set_state` function provided by this module.


Notes
-----

  Browsing the code from XMarshaL_ and pickle.py proved useful for
  ideas.  None of the code is taken from there though.

.. _XMarshaL:  http://www.dezentral.de/soft/XMarshaL

é    N)ÚBytesIOÚStringIOé   )Úversion_registry)ÚFilePathc             C   s8   t ƒ }tjd|d�}|j| ƒ |jƒ  |jdƒ |jƒ S )zBGiven a string (`data`) this gzips the string and returns it.
    Úwb)ÚmodeÚfileobjr   )r   ÚgzipÚGzipFileÚwriteÚcloseÚseekÚread)ÚdataÚsÚwriter© r   ú~/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.6/site-packages/apptools-4.4.0-py3.6.egg/apptools/persistence/state_pickler.pyÚgzip_stringv   s    

r   c             C   sP   t dksttk	r&t| ƒtkr&t| ƒ}nt| ƒ}tjd|d�}|jƒ } |j	ƒ  | S )zOGiven a gzipped string (`data`) this unzips the string and
    returns it.
    é   Úrb)r   r	   )
ÚPY_VERÚbytesÚstrÚtyper   r   r
   r   r   r   )r   r   r   r   r   r   Úgunzip_string�   s    
r   c               @   s   e Zd ZdS )ÚStatePicklerErrorN)Ú__name__Ú
__module__Ú__qualname__r   r   r   r   r   Ž   s   r   c               @   s   e Zd ZdS )ÚStateUnpicklerErrorN)r   r   r    r   r   r   r   r!   ‘   s   r!   c               @   s   e Zd ZdS )ÚStateSetterErrorN)r   r   r    r   r   r   r   r"   ”   s   r"   c               @   s   e Zd ZdZdd„ ZdS )ÚStatezÐUsed to encapsulate the state of an instance in a very
    convenient form.  The '__metadata__' attribute/key is a dictionary
    that has class specific details like the class name, module name
    etc.
    c             K   s   t j| f|Ž | | _d S )N)ÚdictÚ__init__Ú__dict__)ÚselfÚkwr   r   r   r%       s    zState.__init__N)r   r   r    Ú__doc__r%   r   r   r   r   r#   š   s   r#   c               @   s   e Zd ZdZdd„ ZdS )Ú	StateDictzœUsed to encapsulate a dictionary stored in a `State` instance.
    The has_instance attribute specifies if the dict has an instance
    embedded in it.
    c             K   s   t j| f|Ž d| _d S )NF)r$   r%   Úhas_instance)r'   r(   r   r   r   r%   ¬   s    zStateDict.__init__N)r   r   r    r)   r%   r   r   r   r   r*   §   s   r*   c               @   s   e Zd ZdZddd„ZdS )Ú	StateListz—Used to encapsulate a list stored in a `State` instance.  The
    has_instance attribute specifies if the list has an instance
    embedded in it.
    Nc             C   s&   |rt j| |ƒ n
t j| ƒ d| _d S )NF)Úlistr%   r+   )r'   Úseqr   r   r   r%   ¸   s    
zStateList.__init__)N)r   r   r    r)   r%   r   r   r   r   r,   ³   s   r,   c                   s"   e Zd ZdZd‡ fdd„	Z‡  ZS )Ú
StateTuplez™Used to encapsulate a tuple stored in a `State` instance.  The
    has_instance attribute specifies if the tuple has an instance
    embedded in it.
    Nc                s6   |rt t| ƒj| t|ƒƒ}nt t| ƒj| ƒ}d|_|S )NF)Úsuperr/   Ú__new__Útupler+   )Úclsr.   Úobj)Ú	__class__r   r   r1   Ç   s
    zStateTuple.__new__)N)r   r   r    r)   r1   Ú__classcell__r   r   )r5   r   r/   Â   s   r/   c               @   s˜   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	dd„ Z
dd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zd d!„ Zd"d#„ Zd$S )%ÚStatePicklera…  Pickles the state of an object into a dictionary.  The
    dictionary is itself either saved as a pickled file (`dump`) or
    pickled string (`dumps`).  Alternatively, the `dump_state` method
    will return the dictionary that is pickled.

    The format of the state dict is quite strightfoward.  Basic types
    (bool, int, long, float, complex, None, string and unicode) are
    represented as they are.  Everything else is stored as a
    dictionary containing metadata information on the object's type
    etc. and also the actual object in the 'data' key.  For example::

        >>> p = StatePickler()
        >>> p.dump_state(1)
        1
        >>> l = [1,2.0, None, [1,2,3]]
        >>> p.dump_state(l)
        {'data': [1, 2.0, None, {'data': [1, 2, 3], 'type': 'list', 'id': 1}],
         'id': 0,
         'type': 'list'}

    Classes are also represented similarly.  The state in this case is
    obtained from the `__getstate__` method or from the `__dict__`.
    Here is an example::

        >>> class A:
        ...     __version__ = 1  # State version
        ...     def __init__(self):
        ...         self.attribute = 1
        ...
        >>> a = A()
        >>> p = StatePickler()
        >>> p.dump_state(a)
        {'class_name': 'A',
         'data': {'data': {'attribute': 1}, 'type': 'dict', 'id': 2},
         'id': 0,
         'initargs': {'data': (), 'type': 'tuple', 'id': 1},
         'module': '__main__',
         'type': 'instance',
         'version': [(('A', '__main__'), 1)]}

    When pickling data, references are taken care of.  Numeric arrays
    can be pickled and are stored as a gzipped base64 encoded string.

    c             C   s~   | j ƒ  t| jt| jt| jt| jtd ƒ| jt| jt| jt	| j
t| jt| jt| jt| ji}tdkrt| j|t< | j|t< || _d S )Nr   )Ú_clearÚboolÚ_do_basic_typeÚcomplexÚfloatÚintr   r   r   r2   Ú	_do_tupler-   Ú_do_listr$   Ú_do_dictÚNumpyArrayTypeÚ_do_numericr#   Ú	_do_stater   Útype_map)r'   rD   r   r   r   r%      s"    



zStatePickler.__init__c             C   s8   y|j | _W n tk
r    Y nX tj| j|ƒ|ƒ dS )zPPickles the state of the object (`value`) into the passed
        file.
        N)ÚnameÚ	file_nameÚAttributeErrorÚpickleÚdumpÚ_do)r'   ÚvalueÚfiler   r   r   rI     s
    zStatePickler.dumpc             C   s   t j| j|ƒƒS )zPPickles the state of the object (`value`) and returns a
        string.
        )rH   ÚdumpsrJ   )r'   rK   r   r   r   rM      s    zStatePickler.dumpsc             C   s
   | j |ƒS )z°Returns a dictionary or a basic type representing the
        complete state of the object (`value`).

        This value is pickled by the `dump` and `dumps` methods.
        )rJ   )r'   rK   r   r   r   Ú
dump_state&  s    zStatePickler.dump_statec             C   s   d| _ i | _g | _d S )NÚ )rF   Ú	obj_cacheÚ_misc_cache)r'   r   r   r   r8   1  s    zStatePickler._clearc             C   s   dS )z{Checks if the object has traits and ensures that the traits
        are set in the `__dict__` so we can pickle it.
        Nr   )r'   r4   r   r   r   Ú_flush_traits?  s    zStatePickler._flush_traitsc             C   s’   t |ƒ}| j|ƒ}|| jkr&| j|ƒS || jkr>| j| |ƒS t|tƒrR| j|ƒS t|tƒrf| j	|ƒS t|t
ƒrz| j|ƒS t|dƒrŽ| j|ƒS d S )Nr&   )r   Ú_get_idrP   Ú_do_referencerD   Ú
isinstancer2   r>   r-   r?   r$   r@   ÚhasattrÚ_do_instance)r'   r4   Zobj_typeÚkeyr   r   r   rJ   F  s    










zStatePickler._doc             C   s.   yt |ƒ}W n tk
r(   t|ƒ}Y nX |S )N)ÚhashÚ	TypeErrorÚid)r'   rK   rX   r   r   r   rS   Y  s
    zStatePickler._get_idc             C   s$   | j |ƒ}| j}t|ƒ}|||< |S )N)rS   rP   Úlen)r'   rK   rX   ÚcacheÚidxr   r   r   Ú	_register`  s
    
zStatePickler._registerc             C   s   |S )Nr   )r'   rK   r   r   r   r:   g  s    zStatePickler._do_basic_typec             C   s"   | j |ƒ}| j| }td|d d�S )NÚ	reference)r   r[   r   )rS   rP   r$   )r'   rK   rX   r^   r   r   r   rT   j  s    

zStatePickler._do_referencec       
   	   C   sÚ   | j |ƒ | jr&t|tƒr&|j| jƒ f }t|dƒrB|jrB|jƒ }t|dƒrV|jƒ }nt|dƒrj|jƒ }n|j	}|j
dd ƒ | jj||gƒ | j|ƒ}| j|ƒ}| j|ƒ}tj|ƒ}|jj}|jj}	td||	||||d�S )NÚ__getinitargs__Ú__get_pure_state__Ú__getstate__Z__traits_version__Úinstance)r   ÚmoduleÚ
class_nameÚversionr[   Úinitargsr   )rR   rF   rU   r   Zset_relativerV   ra   rb   rc   r&   ÚpoprQ   Úextendr_   rJ   r   Úget_versionr5   r   r   r$   )
r'   rK   ÚargsÚstater^   Ú	args_datar   rg   re   rf   r   r   r   rW   o  s4    








zStatePickler._do_instancec          	   C   sr   |j }|jdƒ}t|ƒ}|jdƒ | jj||gƒ | j|ƒ}| j|ƒ}| j|ƒ}td|d |d |d |||d�S )Nrh   Ú__metadata__rd   re   rf   rg   )r   re   rf   rg   r[   rh   r   )ro   Úgetr$   ri   rQ   rj   r_   rJ   )r'   rK   Úmetadatarl   rm   r^   rn   r   r   r   r   rC   š  s    




zStatePickler._do_statec                s.   ˆ j |ƒ}t‡ fdd„|D ƒƒ}td||d�S )Nc                s   g | ]}ˆ j |ƒ‘qS r   )rJ   )Ú.0Úx)r'   r   r   ú
<listcomp>°  s    z*StatePickler._do_tuple.<locals>.<listcomp>r2   )r   r[   r   )r_   r2   r$   )r'   rK   r^   r   r   )r'   r   r>   ®  s    
zStatePickler._do_tuplec                s*   ˆ j |ƒ}‡ fdd„|D ƒ}td||d�S )Nc                s   g | ]}ˆ j |ƒ‘qS r   )rJ   )rr   rs   )r'   r   r   rt   µ  s    z)StatePickler._do_list.<locals>.<listcomp>r-   )r   r[   r   )r_   r$   )r'   rK   r^   r   r   )r'   r   r?   ³  s    
zStatePickler._do_listc                sL   ˆ j |ƒ}‡ fdd„t|jƒ ƒD ƒ}tttt|jƒ ƒ|ƒƒƒ}td||d�S )Nc                s   g | ]}ˆ j |ƒ‘qS r   )rJ   )rr   rs   )r'   r   r   rt   º  s    z)StatePickler._do_dict.<locals>.<listcomp>r$   )r   r[   r   )r_   r-   Úvaluesr$   ÚzipÚkeys)r'   rK   r^   Úvalsr   r   )r'   r   r@   ¸  s    
zStatePickler._do_dictc             C   sN   | j |ƒ}tdkr*tjttjj|ƒƒƒ}ntjttjj|ƒƒƒ}t	d||d�S )Nr   Únumeric)r   r[   r   )
r_   r   Úbase64Úencodebytesr   ÚnumpyÚndarrayrM   Úencodestringr$   )r'   rK   r^   r   r   r   r   rB   ¾  s
    
zStatePickler._do_numericN)r   r   r    r)   r%   rI   rM   rN   r8   rR   rJ   rS   r_   r:   rT   rW   rC   r>   r?   r@   rB   r   r   r   r   r7   Ó   s$   ,+r7   c               @   s‚   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
d„ Zdd„ Z	d dd„Z
dd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ ZdS )!ÚStateUnpickleraú  Unpickles the state of an object saved using StatePickler.

    Please note that unlike the standard Unpickler, no instances of
    any user class are created.  The data for the state is obtained
    from the file or string, reference objects are setup to refer to
    the same state value and this state is returned in the form
    usually in the form of a dictionary.  For example::

        >>> class A:
        ...     def __init__(self):
        ...         self.attribute = 1
        ...
        >>> a = A()
        >>> p = StatePickler()
        >>> s = p.dumps(a)
        >>> up = StateUnpickler()
        >>> state = up.loads_state(s)
        >>> state.__class__.__name__
        'State'
        >>> state.attribute
        1
        >>> state.__metadata__
        {'class_name': 'A',
         'has_instance': True,
         'id': 0,
         'initargs': (),
         'module': '__main__',
         'type': 'instance',
         'version': [(('A', '__main__'), -1)]}

    Note that the state is actually a `State` instance and is
    navigable just like the original object.  The details of the
    instance are stored in the `__metadata__` attribute.  This is
    highly convenient since it is possible for someone to view and
    modify the state very easily.
    c             C   s,   | j ƒ  | j| j| j| j| j| jdœ| _d S )N)r`   rd   r2   r-   r$   ry   )r8   rT   rW   r>   r?   r@   rB   rD   )r'   r   r   r   r%   ñ  s    zStateUnpickler.__init__c             C   s:   y|j | _W n tk
r    Y nX tj|ƒ}| j|ƒ}|S )z_Returns the state of an object loaded from the pickled data
        in the given file.
        )rE   rF   rG   rH   ÚloadÚ_process)r'   rL   r   Úresultr   r   r   Ú
load_stateû  s    

zStateUnpickler.load_statec             C   s   t j|ƒ}| j|ƒ}|S )zaReturns the state of an object loaded from the pickled data
        in the given string.
        )rH   Úloadsr�   )r'   Ústringr   r‚   r   r   r   Úloads_state  s    

zStateUnpickler.loads_statec             C   s"   d| _ i | _g | _i | _i | _d S )NrO   )rF   Ú
_obj_cacheÚ
_instancesÚ_refsÚ_numeric)r'   r   r   r   r8     s
    zStateUnpickler._clearc             C   s0   t |tƒr||jd< nt |tttfƒr,||_d S )Nr+   )rU   r#   ro   r*   r,   r/   r+   )r'   r4   rK   r   r   r   Ú_set_has_instance  s    
z StateUnpickler._set_has_instancec             C   sJ  | j |ƒ}xRt| jjƒ ƒD ]@\}\}}t|tƒrNt|ƒ}td| ƒ t|ƒ}qtd| ƒ qW x|t| jjƒ ƒD ]j\}}x`|D ]X}| j| }t|tƒr²t|ƒ}td| ƒ t|ƒ}ntd| ƒ t|t	ƒr|| j
j|ƒ q|W qnW xh| j
D ]^}|}xH|�r4d|i}	td| |	|	ƒ | j|	d dƒ |jdƒ}
|d |
… }qîW | j|dƒ qäW |S )Nzresult%s = valzresult%s = xr‚   zval = result%sÚvalTú[)rJ   r-   rŠ   ÚitemsrU   r/   Úexecr‰   r‡   r#   rˆ   Úappendr‹   Úrfind)r'   r   r‚   rX   ÚpathrŒ   Úpathsrs   ÚpthÚnsÚendr   r   r   r�   $  s6    








zStateUnpickler._processrO   c             C   s(   t |ƒtkr | j|d  ||ƒS |S d S )Nr   )r   r$   rD   )r'   r   r’   r   r   r   rJ   N  s    zStateUnpickler._doc             C   s:   |d }|| j kr$| j | j|ƒ n|g| j |< t|d�S )Nr[   )ro   )r‰   r�   r#   )r'   rK   r’   r[   r   r   r   rT   T  s
    
zStateUnpickler._do_referencec             C   sP   |d dkrLd|d krL| j rL|d d }t|d ƒ}|j| j ƒ |j|d< d S )Nrf   r   Ú	file_pathre   r   Zrel_pthÚabs_pth)rF   r   Zset_absoluter˜   )r'   rK   r   Úfpr   r   r   Ú_handle_file_path\  s    z StateUnpickler._handle_file_pathc          	   C   s‚   | j j|ƒ | j|d |d ƒ}| j|ƒ | j|d |ƒ}td|d |d |d |d |d	d
�}tf |Ž}||_|| j|d < |S )Nrh   z.__metadata__["initargs"]r   rd   re   rf   rg   r[   T)r   re   rf   rg   r[   rh   r+   )rˆ   r�   rJ   rš   r$   r#   ro   r‡   )r'   rK   r’   rh   ÚdZmdr‚   r   r   r   rW   e  s     



zStateUnpickler._do_instancec             C   sR   g }x2t |d ƒD ]"\}}|j| j||d|  ƒƒ qW t|ƒ}|| j|d < |S )Nr   z[%d]r[   )Ú	enumerater�   rJ   r/   r‡   )r'   rK   r’   ÚresÚirs   r‚   r   r   r   r>   y  s    zStateUnpickler._do_tuplec             C   sL   t ƒ }x2t|d ƒD ]"\}}|j| j||d|  ƒƒ qW || j|d < |S )Nr   z[%d]r[   )r,   rœ   r�   rJ   r‡   )r'   rK   r’   r‚   rž   rs   r   r   r   r?   �  s
    zStateUnpickler._do_listc             C   sN   t ƒ }x4t|d jƒ ƒD ] \}}| j||d|  ƒ||< qW || j|d < |S )Nr   z["%s"]r[   )r*   r-   rŽ   rJ   r‡   )r'   rK   r’   r‚   rX   rŒ   r   r   r   r@   ˆ  s
    zStateUnpickler._do_dictc             C   s†   t dkrF|d }t|tƒr(|d jdƒ}ttj|ƒƒ}tj|dd�}nt|d j	dƒƒ}tj|ƒ}||f| j
|d < || j|d < |S )Nr   r   zutf-8r   )Úencodingrz   r[   )r   rU   r   Úencoder   rz   Údecodebytesr|   r„   ÚdecoderŠ   r‡   )r'   rK   r’   r   Újunkr‚   r   r   r   rB   �  s    

zStateUnpickler._do_numericN)rO   )r   r   r    r)   r%   rƒ   r†   r8   r‹   r�   rJ   rT   rš   rW   r>   r?   r@   rB   r   r   r   r   r   Ë  s   $
*
	r   c               @   sz   e Zd ZdZdd„ Zddd„Zdd„ Zd	d
„ Zdd„ Zdd„ Z	dd„ Z
dd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd„ ZdS )ÚStateSetterzäThis is a convenience class that helps a user set the
    attributes of an object given its saved state.  For instances it
    checks to see if a `__set_pure_state__` method exists and calls
    that when it sets the state.
    c             C   s(   g | _ t| jt| jt| jt| ji| _	d S )N)
Ú_instance_idsr#   rW   r/   r>   r,   r?   r*   r@   rD   )r'   r   r   r   r%   §  s
    zStateSetter.__init__Nc       	      C   s8  t |tƒ r"|jd dkr"tdƒ‚| j||ƒ | j|ƒ ttj|ƒƒ}|j	dƒ |dkr\g }|dkrhg }|r°d|kr~|| }n2x0|D ](}y|j	|ƒ W q„ t
k
rª   Y q„X q„W x(|D ] }|j	|ƒ | j|||| ƒ q¶W x|D ]}|j	|ƒ qàW x|D ]}| j|||| ƒ qøW x |D ]}| j|||| ƒ �qW dS )a:  Sets the state of the object.

        This is to be used as a means to simplify loading the state of
        an object from its `__setstate__` method using the dictionary
        describing its state.  Note that before the state is set, the
        registered handlers for the particular class are called in
        order to upgrade the version of the state to the latest
        version.

        Parameters
        ----------

        - obj : `object`

          The object whose state is to be set.  If this is `None`
          (default) then the object is created.

        - state : `dict`

          The dictionary representing the state of the object.

        - ignore : `list(str)`

          The list of attributes specified in this list are ignored
          and the state of these attributes are not set (this excludes
          the ones specified in `first` and `last`).  If one specifies
          a '*' then all attributes are ignored except the ones
          specified in `first` and `last`.

        - first : `list(str)`

          The list of attributes specified in this list are set first (in
          order), before any other attributes are set.

        - last : `list(str)`

          The list of attributes specified in this list are set last (in
          order), after all other attributes are set.

        r   rd   z+Can only set the attributes of an instance.ro   NÚ*)rU   r#   ro   r"   Ú_update_and_check_stater_   r-   r$   rw   ÚremoveÚKeyErrorrJ   )	r'   r4   rm   ÚignoreÚfirstÚlastZ
state_keysrE   rX   r   r   r   Úset°  s:    )









zStateSetter.setc             C   s"   t |ƒ}|| jkr| jj|ƒ d S )N)r[   r¥   r�   )r'   r4   r^   r   r   r   r_     s    
zStateSetter._registerc             C   s   t |ƒ| jkS )N)r[   r¥   )r'   r4   r   r   r   Ú_is_registered  s    zStateSetter._is_registeredc             C   s(   t |tƒrdS t |tttfƒr$|jS dS )z…Given something (`value`) that is part of the state this
        returns if the value has an instance embedded in it or not.
        TF)rU   r#   r*   r,   r/   r+   )r'   rK   r   r   r   Ú_has_instance  s
    
zStateSetter._has_instancec                sˆ   |}ˆ j |ƒrtd| ƒ‚t|ttfƒrN‡ fdd„|D ƒ}t|tƒr„t|ƒ}n6t|tƒr„i }x&t|jƒ ƒD ]\}}ˆ j	|ƒ||< qjW |S )zŠReturns the Python representation of the object (usually a
        list, tuple or dict) that has no instances embedded within it.
        zValue has an instance: %sc                s   g | ]}ˆ j |ƒ‘qS r   )Ú	_get_pure)rr   rs   )r'   r   r   rt   )  s    z)StateSetter._get_pure.<locals>.<listcomp>)
r¯   r"   rU   r,   r/   r2   r*   r-   rŽ   r°   )r'   rK   r‚   ÚkÚvr   )r'   r   r°     s    




zStateSetter._get_purec             C   sd   t jj|ƒ |j}|j}|d |jkr<td|j|d f ƒ‚|d |jkr`td|j|d f ƒ‚dS )zmUpdates the state from the registry and then checks if the
        object and state have same class.
        rf   z=Instance (%s) and state (%s) do not have the same class name!re   z>Instance (%s) and state (%s) do not have the same module name!N)r   ÚregistryÚupdatero   r5   r   r"   r   )r'   r4   rm   rq   r3   r   r   r   r§   2  s    z#StateSetter._update_and_check_statec             C   s²   yt ||ƒ}W n$ tk
r2   td||f ƒ‚Y nX t|ttttfƒr¢| j|ƒsh| j	|ƒ}t
|||ƒ q®t|tƒrŽt
||| jt ||ƒ|ƒƒ q®| jt ||ƒ|ƒ nt
|||ƒ d S )Nz/Object %s does not have an attribute called: %s)ÚgetattrrG   r"   rU   r#   r*   r,   r/   r¯   r°   Úsetattrr>   Ú
_do_object)r'   r4   rX   rK   Úattrr‚   r   r   r   rJ   I  s    


zStateSetter._doc             C   s   | j |j ||ƒ d S )N)rD   r5   )r'   r4   rm   r   r   r   r·   ]  s    zStateSetter._do_objectc             C   sŠ   | j |ƒrd S | j|ƒ |j}t|dƒr@| j||ƒ |j|ƒ nFd|d krz| j||ƒ | jtf |Žƒ}|d= |j|ƒ n| j	||ƒ d S )NÚ__set_pure_state__Útvtk_classesre   ro   )
r®   r_   ro   rV   r§   r¹   r°   r*   Ú__setstate__r­   )r'   r4   rm   rq   Útmpr   r   r   rW   `  s    


zStateSetter._do_instancec             C   s4   | j |ƒs| j|ƒS t|ƒ}| j||ƒ t|ƒS d S )N)r¯   r°   r-   r?   r2   )r'   r4   rm   r‚   r   r   r   r>   s  s
    

zStateSetter._do_tuplec             C   sŒ   t |ƒt |ƒkr€xvtt |ƒƒD ]\}| j|| ƒsD| j|| ƒ||< qt|| tƒrf| j|| ƒ||< q| j|| || ƒ qW ntdƒ‚d S )Nz+Cannot set state of list of incorrect size.)	r\   Úranger¯   r°   rU   r2   r>   r·   r"   )r'   r4   rm   rž   r   r   r   r?   {  s    zStateSetter._do_listc             C   sb   x\t |jƒ ƒD ]L\}}| j|ƒs0| j|ƒ||< qt|tƒrJ| j|ƒ||< q| j|| |ƒ qW d S )N)r-   rŽ   r¯   r°   rU   r2   r>   r·   )r'   r4   rm   rX   rK   r   r   r   r@   ‰  s    

zStateSetter._do_dict)NNN)r   r   r    r)   r%   r­   r_   r®   r¯   r°   r§   rJ   r·   rW   r>   r?   r@   r   r   r   r   r¤   ¡  s   	
]
r¤   c             C   s.   t | dƒr| S t| tƒr"t| dƒS tdƒ‚d S )Nr   r   z(Given object is neither a file or String)rV   rU   r   ÚopenrZ   )Úfr   r   r   Ú_get_file_read–  s
    


rÀ   c             C   s.   t | dƒr| S t| tƒr"t| dƒS tdƒ‚d S )Nr   r   z(Given object is neither a file or String)rV   rU   r   r¾   rZ   )r¿   r   r   r   Ú_get_file_writež  s
    


rÁ   c             C   s:   t |ƒ}ztƒ j| |ƒ W d|jƒ  ||k	r4|jƒ  X dS )zWPickles the state of the object (`value`) into the passed file
    (or file name).
    N)rÁ   r7   rI   Úflushr   )rK   rL   r¿   r   r   r   rI   ª  s    rI   c             C   s   t ƒ j| ƒS )zDPickles the state of the object (`value`) and returns a string.
    )r7   rM   )rK   r   r   r   rM   ·  s    rM   c             C   s0   t | ƒ}ztƒ j|ƒ}W d|| k	r*|jƒ  X |S )zfReturns the state of an object loaded from the pickled data in
    the given file (or file name).
    N)rÀ   r   rƒ   r   )rL   r¿   rm   r   r   r   rƒ   ½  s    
rƒ   c             C   s   t ƒ j| ƒS )zYReturns the state of an object loaded from the pickled data
    in the given string.
    )r   r†   )r…   r   r   r   r†   Ê  s    r†   c             C   s   t | ƒ}t|ƒS )zŸReturns the state of the object (usually as a dictionary).  The
    returned state may be used directy to set the state of the object
    via `set_state`.
    )rM   r†   )r4   r   r   r   r   Ú	get_stateÑ  s    rÃ   c             C   s   t ƒ j| ||||ƒ d S )N)r¤   r­   )r4   rm   rª   r«   r¬   r   r   r   Ú	set_stateÚ  s    rÄ   c             C   s   t jj| ƒ dS )z©Given the state of an object, this updates the state to the
    latest version using the handlers given in the version registry.
    The state is modified in-place.
    N)r   r³   r´   )rm   r   r   r   Úupdate_stateß  s    rÅ   c             C   sœ   t | tƒ rd| jkrtdƒ‚| j}|jdƒ}|jdƒ}d|krXddlm} t||ƒƒ S |d }|jrnt	dƒ‚t
|tƒ tƒ |ƒ tj| }t||ƒ}||Ž S )	z3Create an instance from the state if possible.
    rf   zNo class information in statere   rº   r   )Útvtkrh   z$Cannot unpickle non-trivial initargs)rU   r#   ro   r"   rp   Ztvtk.apirÆ   rµ   r+   r!   Ú
__import__ÚglobalsÚlocalsÚsysÚmodules)rm   rq   rf   Úmod_namerÆ   rh   Úmodr3   r   r   r   Úcreate_instanceç  s     




rÎ   )NNN).r)   rz   rÊ   ÚtypesrH   r
   Úior   r   r|   rO   r   r—   r   Úversion_infor   r   ÚarrayrA   r   r   Ú	Exceptionr   r!   r"   r$   r#   r*   r-   r,   r2   r/   r7   r   r¤   rÀ   rÁ   rI   rM   rƒ   r†   rÃ   rÄ   r­   rÅ   rÎ   r   r   r   r   Ú<module>_   sJ   
 y W v	

