
lR\                 @   sT  d  Z  d d l m Z d d l m Z d d l m Z d d l m Z m Z d Z	 d Z
 d Z d	 Z d
 Z d Z d Z Gd d   d e  Z Gd d   d e  Z Gd d   d e  Z d d   Z d d d  Z d d d  Z Gd d   d e  Z Gd d   d e  Z Gd d   d e  Z Gd  d!   d! e  Z Gd" d#   d# e  Z d S)$z
    tablib.core
    ~~~~~~~~~~~

    This module implements the central Tablib objects.

    :copyright: (c) 2016 by Kenneth Reitz.
    :license: MIT, see LICENSE for more details.
    )copy)
itemgetter)formats)OrderedDictunicodetablibz0.12.1i  zKenneth ReitzMITzCopyright 2017 Kenneth ReitzZrestructuredtextc               @   s  e  Z d  Z d Z d d g Z e   e   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 e d" d#    Z e d$ d%    Z d& d'   Z d( S))Rowz/Internal Row object. Mainly used for filtering._rowtagsc             C   s"   t  |  |  _ t  |  |  _ d  S)N)listr
   r   )selfrowr    r   @/var/www/dbchiro/venv/lib/python3.4/site-packages/tablib/core.py__init__"   s    zRow.__init__c             C   s   d d   |  j  D S)Nc             s   s   |  ] } | Vq d  S)Nr   ).0colr   r   r   	<genexpr>'   s    zRow.__iter__.<locals>.<genexpr>)r
   )r   r   r   r   __iter__&   s    zRow.__iter__c             C   s   t  |  j  S)N)lenr
   )r   r   r   r   __len__)   s    zRow.__len__c             C   s   t  |  j  S)N)reprr
   )r   r   r   r   __repr__,   s    zRow.__repr__c             C   s   |  j  | |  S)N)r
   )r   ijr   r   r   __getslice__/   s    zRow.__getslice__c             C   s   |  j  | S)N)r
   )r   r   r   r   r   __getitem__2   s    zRow.__getitem__c             C   s   | |  j  | <d  S)N)r
   )r   r   valuer   r   r   __setitem__5   s    zRow.__setitem__c             C   s   |  j  | =d  S)N)r
   )r   r   r   r   r   __delitem__8   s    zRow.__delitem__c             C   s:   t    } x* |  j D] } t |  |  } | | | <q W| S)N)dict	__slots__getattr)r   slotsZslot	attributer   r   r   __getstate__;   s
    	zRow.__getstate__c             C   s7   x0 t  | j    D] \ } } t |  | |  q Wd  S)N)r   itemssetattr)r   statekvr   r   r   __setstate__E   s     zRow.__setstate__c             C   s   |  j  d |  d  S)Nr   )insert)r   r   r   r   r   rpushH   s    z	Row.rpushc             C   s   |  j  t |  |  d  S)N)r-   r   )r   r   r   r   r   lpushK   s    z	Row.lpushc             C   s   |  j  |  d  S)N)r.   )r   r   r   r   r   appendN   s    z
Row.appendc             C   s   |  j  j | |  d  S)N)r
   r-   )r   indexr   r   r   r   r-   Q   s    z
Row.insertc             C   s   | |  j  k S)N)r
   )r   itemr   r   r   __contains__T   s    zRow.__contains__c             C   s   t  |  j  S)z%Tuple representation of :class:`Row`.)tupler
   )r   r   r   r   r4   W   s    z	Row.tuplec             C   s   t  |  j  S)z$List representation of :class:`Row`.)r   r
   )r   r   r   r   r   \   s    zRow.listc             C   sS   | d k r d St  | t  r, | |  j k St t t |  t |  j  @  Sd S)z)Returns true if current row contains tag.NF)
isinstancestrr   boolr   set)r   tagr   r   r   has_taga   s
    zRow.has_tagN)__name__
__module____qualname____doc__r"   r   r   r   r   r   r   r   r   r    r&   r,   r.   r/   r0   r-   r3   propertyr4   r:   r   r   r   r   r	      s(   
r	   c               @   sp  e  Z d  Z d Z i  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 e d d    Z d d d d d  Z d d d d  Z d d   Z d d   Z e e e  Z d d    Z d! d"   Z e e e  Z d# d$   Z e d% d&    Z e d' d(    Z d d) d*  Z d+ d,   Z e d- d.    Z e d/ d0    Z e d1 d2    Z e d3 d4    Z  e d5 d6    Z! e d7 d8    Z" e d9 d:    Z# e d; d<    Z$ e d= d>    Z% e d? d@    Z& e dA dB    Z' e(   dC dD  Z) e(   dE dF  Z* e(   dG dH  Z+ e(   dI dJ  Z, e(   dK dL  Z- dM dN   Z. dO dP   Z/ dQ dR   Z0 d d dS dT  Z1 d dU dV  Z2 d dW dX  Z3 dY dZ d[  Z4 dY d\ d]  Z5 d d^ d_  Z6 d` da   Z7 db dc   Z8 dd de   Z9 d df dg  Z: dh di   Z; dj dk   Z< dl dm   Z= dn do   Z> dp dq   Z? d d dr ds  Z@ d S)tDataseta  The :class:`Dataset` object is the heart of Tablib. It provides all core
    functionality.

    Usually you create a :class:`Dataset` instance in your main module, and append
    rows as you collect data. ::

        data = tablib.Dataset()
        data.headers = ('name', 'age')

        for (name, age) in some_collector():
            data.append((name, age))


    Setting columns is similar. The column data length must equal the
    current height of the data and headers must be set ::

        data = tablib.Dataset()
        data.headers = ('first_name', 'last_name')

        data.append(('John', 'Adams'))
        data.append(('George', 'Washington'))

        data.append_col((90, 67), header='age')


    You can also set rows and headers upon instantiation. This is useful if
    dealing with dozens or hundreds of :class:`Dataset` objects. ::

        headers = ('first_name', 'last_name')
        data = [('John', 'Adams'), ('George', 'Washington')]

        data = tablib.Dataset(*data, headers=headers)

    :param \*args: (optional) list of rows to populate Dataset
    :param headers: (optional) list strings for Dataset header row
    :param title: (optional) string to use as title of the Dataset


    .. admonition:: Format Attributes Definition

     If you look at the code, the various output/import formats are not
     defined within the :class:`Dataset` object. To add support for a new format, see
     :ref:`Adding New Formats <newformats>`.

    c             O   si   t  d d   | D  |  _ d  |  _ g  |  _ g  |  _ | j d  |  _ | j d  |  _ |  j   d  S)Nc             s   s   |  ] } t  |  Vq d  S)N)r	   )r   argr   r   r   r      s    z#Dataset.__init__.<locals>.<genexpr>headerstitle)	r   _data_Dataset__headers_separators_formattersgetrB   rC   _register_formats)r   argskwargsr   r   r   r      s    			zDataset.__init__c             C   s   |  j  S)N)height)r   r   r   r   r      s    zDataset.__len__c                s   t  | t  s t  | t  rb | |  j k rY |  j j |      f d d   |  j D St  n4 |  j | } t  | t  r | j Sd d   | D Sd  S)Nc                s   g  |  ] } |    q Sr   r   )r   r   )posr   r   
<listcomp>   s   	 z'Dataset.__getitem__.<locals>.<listcomp>c             S   s   g  |  ] } | j   q Sr   )r4   )r   resultr   r   r   rN      s   	 )	r5   r6   r   rB   r1   rD   KeyErrorr	   r4   )r   keyZ_resultsr   )rM   r   r      s    	zDataset.__getitem__c             C   s$   |  j  |  t |  |  j | <d  S)N)	_validater	   rD   )r   rQ   r   r   r   r   r      s    zDataset.__setitem__c             C   s   t  | t  s t  | t  r | |  j k r |  j j |  } |  j | =x: t |  j  D]  \ } } | | =| |  j | <qY Wq t  n
 |  j | =d  S)N)r5   r6   r   rB   r1   	enumeraterD   rP   )r   rQ   rM   r   r   r   r   r   r       s    
	zDataset.__delitem__c             C   s2   y d |  j  j   SWn t k
 r- d SYn Xd  S)Nz<%s dataset>z<dataset object>)rC   lowerAttributeError)r   r   r   r   r      s    zDataset.__repr__c                s   g  } |  j  r/ | j d d   |  j  D  n  | j d d   |  j D  d d   | D } t t t t |     } |  j  r | j d d d   | D  n  d j	 d	 d   t
 |  D    d
 j	   f d d   | D  S)Nc             S   s   g  |  ] } t  |   q Sr   )r   )r   hr   r   r   rN      s   	 z'Dataset.__unicode__.<locals>.<listcomp>c             s   s$   |  ] } t  t t |   Vq d  S)N)r   mapr   )r   r   r   r   r   r      s    z&Dataset.__unicode__.<locals>.<genexpr>c             S   s%   g  |  ] } t  t t |    q Sr   )r   rW   r   )r   r   r   r   r   rN      s   	    c             S   s   g  |  ] } d  |  q S)-r   )r   lengthr   r   r   rN      s   	 |c             s   s   |  ] } d  | Vq d S)z{%s:%s}Nr   )r   r2   r   r   r   r      s    
c             3   s   |  ] }   j  |   Vq d  S)N)format)r   r   )format_stringr   r   r      s    )rE   r0   extendrD   r   rW   maxzipr-   joinrS   )r   rO   ZlensZ
field_lensr   )r^   r   __unicode__   s    	 	 "zDataset.__unicode__c             C   s
   |  j    S)N)rc   )r   r   r   r   __str__   s    zDataset.__str__c             C   s  xt  j D]	} y yv t |  | j t | j | j   t |  d | j | j  t |  d | j | j  | j | j f |  j | j <Wna t k
 r t |  | j t | j   t |  d | j | j  | j d f |  j | j <Yn XWq
 t k
 rd |  j | j <Yq
 Xq
 Wd S)zAdds format properties.zget_%szset_%sN)NN)	r   	availabler(   rC   r?   
export_set
import_set_formatsrU   )clsfmtr   r   r   rI      s    " "zDataset._register_formatsNFc                s   | r-   j  r$ t |    j  k n d } nj | ru t |  d k  rN d } q   j rl t |    j k n d } n" t   f d d     j D  } | r d S| s t  n  d Sd S)z>Assures size of every row in dataset is of proper proportions.TrX   c             3   s$   |  ] } t  |    j k Vq d  S)N)r   width)r   x)r   r   r   r     s    z$Dataset._validate.<locals>.<genexpr>FN)rk   r   rL   allrD   InvalidDimensions)r   r   r   ZsafetyZis_validr   )r   r   rR     s    '	'"	zDataset._validateTc                sB  t   j  } | r t   n t    j r x t |  D] \ } } x  j D] \ } } y\ | d k r xI t |  D]  \ } }	 | |	  | | | <qx Wn | | |  | | | <WqP t k
 r t  YqP XqP Wq: Wn   j r+| r   f d d   | D }
 q>t   j  g t  |  }
 n d d   | D }
 |
 S)z=Packages Dataset into lists of dictionaries for transmission.Nc                s.   g  |  ]$ }   t  t  j |     q Sr   )r   ra   rB   )r   data_row)	dict_packr   r   r   rN   =  s   	 z$Dataset._package.<locals>.<listcomp>c             S   s   g  |  ] } t  |   q Sr   )r   )r   r   r   r   r   rN   A  s   	 )	r   rD   r   r!   rG   rS   
IndexErrorInvalidDatasetIndexrB   )r   ZdictsorderedrD   Zrow_ir   r   callbackr   cdatar   )rp   r   r   _package"  s(    			zDataset._packagec             C   s   |  j  S)zAn *optional* list of strings to be used for header rows and attribute names.

        This must be set manually. The given list length must equal :class:`Dataset.width`.

        )rE   )r   r   r   r   _get_headersG  s    zDataset._get_headersc             C   sQ   |  j  |  | rD y t |  |  _ WqM t k
 r@ t  YqM Xn	 d |  _ d S)zValidating headers setter.N)rR   r   rE   	TypeError)r   Z
collectionr   r   r   _set_headersP  s    zDataset._set_headersc             C   s
   |  j    S)a  A native Python representation of the :class:`Dataset` object. If headers have
        been set, a list of Python dictionaries will be returned. If no headers have been set,
        a list of tuples (rows) will be returned instead.

        A dataset object can also be imported by setting the `Dataset.dict` attribute: ::

            data = tablib.Dataset()
            data.dict = [{'age': 90, 'first_name': 'Kenneth', 'last_name': 'Reitz'}]

        )rw   )r   r   r   r   	_get_dict^  s    zDataset._get_dictc             C   s   t  |  s d St | d t  rT |  j   x | D] } |  j t |   q4 Wno t | d t  r |  j   t | d j    |  _ x6 | D]% } |  j t t | j	      q Wn t
  d S)a  A native Python representation of the Dataset object. If headers have been
        set, a list of Python dictionaries will be returned. If no headers have been
        set, a list of tuples (rows) will be returned instead.

        A dataset object can also be imported by setting the :class:`Dataset.dict` attribute. ::

            data = tablib.Dataset()
            data.dict = [{'age': 90, 'first_name': 'Kenneth', 'last_name': 'Reitz'}]

        Nr   )r   r5   r   wiper0   r	   r!   keysrB   valuesUnsupportedFormat)r   pickler   r   r   r   	_set_dictl  s    

&zDataset._set_dictc             C   s   t  |  } |  j r* | j d  g } n g  } t |  d k rt t | d d  rt t  t | d |  j   } n  t | |  } | S)z,Prepares the given column for insert/append.r   rX   __call__)r   rB   popr   hasattrrW   rD   r4   )r   r   headerr   r   r   
_clean_col  s    	%zDataset._clean_colc             C   s   t  |  j  S)zfThe number of rows currently in the :class:`Dataset`.
           Cannot be directly modified.
        )r   rD   )r   r   r   r   rL     s    zDataset.heightc             C   sX   y t  |  j d  SWn< t k
 rS y t  |  j  SWn t k
 rN d SYn XYn Xd S)ziThe number of columns currently in the :class:`Dataset`.
           Cannot be directly modified.
        r   N)r   rD   rq   rB   ry   )r   r   r   r   rk     s    zDataset.widthc             K   sb   | s t  |  } n  |  j j | d  \ } } | sN t d j |    n  | |  | |  |  S)z
        Import `in_stream` to the :class:`Dataset` object using the `format`.

        :param \*\*kwargs: (optional) custom configuration to the format `import_set`.
        NzFormat {0} cannot be imported.)NN)detect_formatrh   rH   r   r]   )r   	in_streamr]   rK   rf   rg   r   r   r   load  s    zDataset.loadc             K   sF   |  j  j | d  \ } } | s9 t d j |    n  | |  |  S)z
        Export :class:`Dataset` object to `format`.

        :param \*\*kwargs: (optional) custom configuration to the format `export_set`.
        NzFormat {0} cannot be exported.)NN)rh   rH   r   r]   )r   r]   rK   rf   rg   r   r   r   export  s    zDataset.exportc               C   s   d S)a  A Legacy Excel Spreadsheet representation of the :class:`Dataset` object, with :ref:`separators`. Cannot be set.

        .. note::

            XLS files are limited to a maximum of 65,000 rows. Use :class:`Dataset.xlsx` to avoid this limitation.

         .. admonition:: Binary Warning

             :class:`Dataset.xls` contains binary data, so make sure to write in binary mode::

                with open('output.xls', 'wb') as f:
                    f.write(data.xls)
        Nr   r   r   r   r   xls  s    zDataset.xlsc               C   s   d S)a_  An Excel '07+ Spreadsheet representation of the :class:`Dataset` object, with :ref:`separators`. Cannot be set.

         .. admonition:: Binary Warning

             :class:`Dataset.xlsx` contains binary data, so make sure to write in binary mode::

                with open('output.xlsx', 'wb') as f:
                    f.write(data.xlsx)
        Nr   r   r   r   r   xlsx  s    zDataset.xlsxc               C   s   d S)a^  An OpenDocument Spreadsheet representation of the :class:`Dataset` object, with :ref:`separators`. Cannot be set.

         .. admonition:: Binary Warning

             :class:`Dataset.ods` contains binary data, so make sure to write in binary mode::

                with open('output.ods', 'wb') as f:
                    f.write(data.ods)
        Nr   r   r   r   r   ods  s    zDataset.odsc               C   s   d S)ac  A CSV representation of the :class:`Dataset` object. The top row will contain
        headers, if they have been set. Otherwise, the top row will contain
        the first row of the dataset.

        A dataset object can also be imported by setting the :class:`Dataset.csv` attribute. ::

            data = tablib.Dataset()
            data.csv = 'age, first_name, last_name\n90, John, Adams'

        Import assumes (for now) that headers exist.

        .. admonition:: Binary Warning

             :class:`Dataset.csv` uses \r\n line endings by default, so make
             sure to write in binary mode::

                 with open('output.csv', 'wb') as f:
                     f.write(data.csv)

             If you do not do this, and you export the file on Windows, your
             CSV file will open in Excel with a blank line between each row.
        Nr   r   r   r   r   csv  s    zDataset.csvc               C   s   d S)a  A TSV representation of the :class:`Dataset` object. The top row will contain
        headers, if they have been set. Otherwise, the top row will contain
        the first row of the dataset.

        A dataset object can also be imported by setting the :class:`Dataset.tsv` attribute. ::

            data = tablib.Dataset()
            data.tsv = 'age	first_name	last_name\n90	John	Adams'

        Import assumes (for now) that headers exist.
        Nr   r   r   r   r   tsv  s    zDataset.tsvc               C   s   d S)a  A YAML representation of the :class:`Dataset` object. If headers have been
        set, a YAML list of objects will be returned. If no headers have
        been set, a YAML list of lists (rows) will be returned instead.

        A dataset object can also be imported by setting the :class:`Dataset.yaml` attribute: ::

            data = tablib.Dataset()
            data.yaml = '- {age: 90, first_name: John, last_name: Adams}'

        Import assumes (for now) that headers exist.
        Nr   r   r   r   r   yaml.  s    zDataset.yamlc               C   s   d S)a4  A DataFrame representation of the :class:`Dataset` object.

        A dataset object can also be imported by setting the :class:`Dataset.df` attribute: ::

            data = tablib.Dataset()
            data.df = DataFrame(np.random.randn(6,4))

        Import assumes (for now) that headers exist.
        Nr   r   r   r   r   df=  s    z
Dataset.dfc               C   s   d S)a  A JSON representation of the :class:`Dataset` object. If headers have been
        set, a JSON list of objects will be returned. If no headers have
        been set, a JSON list of lists (rows) will be returned instead.

        A dataset object can also be imported by setting the :class:`Dataset.json` attribute: ::

            data = tablib.Dataset()
            data.json = '[{"age": 90, "first_name": "John", "last_name": "Adams"}]'

        Import assumes (for now) that headers exist.
        Nr   r   r   r   r   jsonJ  s    zDataset.jsonc               C   s   d S)zA HTML table representation of the :class:`Dataset` object. If
        headers have been set, they will be used as table headers.

        ..notice:: This method can be used for export only.
        Nr   r   r   r   r   htmlY  s    zDataset.htmlc               C   s   d S)a  A dBASE representation of the :class:`Dataset` object.

        A dataset object can also be imported by setting the
        :class:`Dataset.dbf` attribute. ::

            # To import data from an existing DBF file:
            data = tablib.Dataset()
            data.dbf = open('existing_table.dbf').read()

            # to import data from an ASCII-encoded bytestring:
            data = tablib.Dataset()
            data.dbf = '<bytestring of tabular data>'

        .. admonition:: Binary Warning

            :class:`Dataset.dbf` contains binary data, so make sure to write in binary mode::

                with open('output.dbf', 'wb') as f:
                    f.write(data.dbf)
        Nr   r   r   r   r   dbfb  s    zDataset.dbfc               C   s   d S)zA LaTeX booktabs representation of the :class:`Dataset` object. If a
        title has been set, it will be exported as the table caption.

        .. note:: This method can be used for export only.
        Nr   r   r   r   r   latex{  s    zDataset.latexc             C   s0   |  j  |  |  j j | t | d |  d S)zInserts a row to the :class:`Dataset` at the given index.

        Rows inserted must be the correct size (height or width).

        The default behaviour is to insert the given row to the :class:`Dataset`
        object at the given index.
       r   N)rR   rD   r-   r	   )r   r1   r   r   r   r   r   r-     s    	zDataset.insertc             C   s    |  j  |  j d | d | d S)zyAdds a row to the end of the :class:`Dataset`.
        See :class:`Dataset.insert` for additional documentation.
        r   r   N)r-   rL   )r   r   r   r   r   r   r.     s    zDataset.rpushc             C   s   |  j  d d | d | d S)zyAdds a row to the top of the :class:`Dataset`.
        See :class:`Dataset.insert` for additional documentation.
        r   r   r   N)r-   )r   r   r   r   r   r   r/     s    zDataset.lpushc             C   s   |  j  | |  d S)znAdds a row to the :class:`Dataset`.
        See :class:`Dataset.insert` for additional documentation.
        N)r.   )r   r   r   r   r   r   r0     s    zDataset.appendc             C   s%   x | D] } |  j  | |  q Wd S)zZAdds a list of rows to the :class:`Dataset` using
        :class:`Dataset.append`
        N)r0   )r   rowsr   r   r   r   r   r_     s    zDataset.extendc             C   s   |  d } |  d =| S)z:Removes and returns the first row of the :class:`Dataset`.r   r   )r   cacher   r   r   lpop  s    
zDataset.lpopc             C   s   |  d } |  d =| S)z9Removes and returns the last row of the :class:`Dataset`.rX   r   r   )r   r   r   r   r   rpop  s    
zDataset.rpopc             C   s
   |  j    S)z9Removes and returns the last row of the :class:`Dataset`.)r   )r   r   r   r   r     s    zDataset.popc             C   s)  | d k r g  } n  t  | d  r? t t | |  j   } n  |  j |  } |  j d |  |  j r | sy t    n* | r |  j d k r t	 |  r t
  n  |  j j | |  n  |  j r|  j rxW t |  j  D]- \ } } | j | | |  | |  j | <q Wn d d   | D |  _ d S)a  Inserts a column to the :class:`Dataset` at the given index.

        Columns inserted must be the correct height.

        You can also insert a column of a single callable object, which will
        add a new column with the return values of the callable each as an
        item in the column. ::

            data.append_col(col=random.randint)

        If inserting a column, and :class:`Dataset.headers` is set, the
        header attribute must be set, and will be considered the header for
        that row.

        See :ref:`dyncols` for an in-depth example.

        .. versionchanged:: 0.9.0
           If inserting a column, and :class:`Dataset.headers` is set, the
           header attribute must be set, and will be considered the header for
           that row.

        .. versionadded:: 0.9.0
           If inserting a row, you can add :ref:`tags <tags>` to the row you are inserting.
           This gives you the ability to :class:`filter <Dataset.filter>` your
           :class:`Dataset` later.

        Nr   r   r   c             S   s   g  |  ] } t  | g   q Sr   )r	   )r   r   r   r   r   rN     s   	 z&Dataset.insert_col.<locals>.<listcomp>)r   r   rW   rD   r   rR   rB   HeadersNeededrL   r   rn   r-   rk   rS   )r   r1   r   r   r   r   r   r   r   
insert_col  s"    		!	zDataset.insert_colc             C   s   |  j  |  j | d | d S)z|Adds a column to the end of the :class:`Dataset`.
        See :class:`Dataset.insert` for additional documentation.
        r   N)r   rk   )r   r   r   r   r   r   	rpush_col  s    zDataset.rpush_colc             C   s   |  j  d | d | d S)z|Adds a column to the top of the :class:`Dataset`.
        See :class:`Dataset.insert` for additional documentation.
        r   r   N)r   )r   r   r   r   r   r   	lpush_col  s    zDataset.lpush_colrY   c             C   s    | | f } |  j  j |  d S)z4Adds a separator to :class:`Dataset` at given index.N)rF   r0   )r   r1   textsepr   r   r   insert_separator   s    zDataset.insert_separatorc             C   sT   |  j  s$ |  j r |  j n d } n |  j r: |  j d n d } |  j | |  d S)z=Adds a :ref:`separator <separators>` to the :class:`Dataset`.r   rX   N)rB   rL   r   )r   r   r1   r   r   r   append_separator'  s    	zDataset.append_separatorc             C   s   |  j  | |  d S)zuAdds a column to the :class:`Dataset`.
        See :class:`Dataset.insert_col` for additional documentation.
        N)r   )r   r   r   r   r   r   
append_col3  s    zDataset.append_colc                s     f d d   |  j  D S)z@Returns the column from the :class:`Dataset` at the given index.c                s   g  |  ] } |    q Sr   r   )r   r   )r1   r   r   rN   >  s   	 z#Dataset.get_col.<locals>.<listcomp>)rD   )r   r1   r   )r1   r   get_col;  s    zDataset.get_colc             C   sn   t  | t  r< | |  j k r3 |  j j |  } q< t  n  | |  j k sd |  j j | | f  n t  d S)a  Adds a :ref:`formatter` to the :class:`Dataset`.

        .. versionadded:: 0.9.5
           :param col: column to. Accepts index int or header str.
           :param handler: reference to callback function to execute
           against each cell value.
        T)	r5   r6   rB   r1   rP   rk   rG   r0   rr   )r   r   handlerr   r   r   add_formatterE  s    		zDataset.add_formatterc                s/   t  |   }   f d d   | j D | _ | S)zReturns a new instance of the :class:`Dataset`, excluding any rows
        that do not contain the given :ref:`tags <tags>`.
        c                s%   g  |  ] } | j     r |  q Sr   )r:   )r   r   )r9   r   r   rN   a  s   	 z"Dataset.filter.<locals>.<listcomp>)r   rD   )r   r9   _dsetr   )r9   r   filter\  s    zDataset.filterc                sT  t  | t  s t  | t  r |  j s0 t  n  t |  j d t |  d | } t d |  j d |  j	  } x | D]2     f d d   |  j D } | j
 d |  qs Wn |  j r |  j | } n  t |  j d t |  d | } t d |  j d |  j	  } xL | D]D   |  j r6  f d d   |  j D } n   } | j
 d |  qW| S)	a  Sort a :class:`Dataset` by a specific column, given string (for
        header) or integer (for column index). The order can be reversed by
        setting ``reverse`` to ``True``.

        Returns a new :class:`Dataset` instance where columns have been
        sorted.
        rQ   reverserB   rC   c                s   g  |  ] }   |  q Sr   r   )r   rQ   )r2   r   r   rN   x  s   	 z Dataset.sort.<locals>.<listcomp>r   c                s   g  |  ] }   |  q Sr   r   )r   rQ   )r2   r   r   rN     s   	 )r5   r6   r   rB   r   sortedr!   r   r@   rC   r0   )r   r   r   Z_sortedr   r   r   )r2   r   sortf  s$    			!	!	zDataset.sortc             C   s   |  s
 d St    } |  j d g |  |  j d } | | _ xh t |  j  D]W \ } } | |  j d k rp qK n  | g |  j |  } t |  } | j d |  qK W| S)zTranspose a :class:`Dataset`, turning rows into columns and vice
        versa, returning a new ``Dataset`` instance. The first row of the
        original instance becomes the new header row.Nr   r   )r@   rB   rS   r   r	   r0   )r   r   new_headersr1   columnZrow_datar   r   r   	transpose  s    		zDataset.transposec             C   s   t  | t  s d S|  j | j k r. t  n  t |   } d d   | j D } d d   | j D } | j |  | | _ | S)zStack two :class:`Dataset` instances together by
        joining at the row level, and return new combined
        ``Dataset`` instance.Nc             S   s   g  |  ] } |  q Sr   r   )r   r   r   r   r   rN     s   	 z!Dataset.stack.<locals>.<listcomp>c             S   s   g  |  ] } |  q Sr   r   )r   r   r   r   r   rN     s   	 )r5   r@   rk   rn   r   rD   r_   )r   otherr   Zrows_to_stackZ
other_rowsr   r   r   stack  s    		zDataset.stackc             C   s   t  | t  s d S|  j s% | j rE |  j s9 | j rE t  qE n  |  j | j k r` t  n  y |  j | j } Wn t k
 r d } Yn Xt   } x% |  j D] } | j d |  |  q Wx% | j D] } | j d | |  q W| | _ | S)zStack two :class:`Dataset` instances together by
        joining at the column level, and return a new
        combined ``Dataset`` instance. If either ``Dataset``
        has headers set, than the other must as well.Nr   )r5   r@   rB   r   rL   rn   ry   r   )r   r   r   r   r   r   r   r   
stack_cols  s$    			zDataset.stack_colsc                s6   t        f d d   |  j D |  j d d  <d S)ziRemoves all duplicate rows from the :class:`Dataset` object
        while maintaining the original order.c                s=   g  |  ]3 } t  |    k p0   j t  |   s |  q Sr   )r4   add)r   r   )seenr   r   rN     s   	 z-Dataset.remove_duplicates.<locals>.<listcomp>N)r8   rD   )r   r   )r   r   remove_duplicates  s    	zDataset.remove_duplicatesc             C   s   t    |  _ d |  _ d S)zARemoves all content and headers from the :class:`Dataset` object.N)r   rD   rE   )r   r   r   r   r|     s    zDataset.wipec       	         s=    s
 d S| d k r. t  t   j   } n  | d k rL t    j  } n    f d d   | D }   f d d   | D } t   } t  |  | _ g  | _ x t   j  D] \ } } g  } xL | j D]A } |   j k r  j j |  } | j | |  q t	  q W| | k r | j d t
 |   q q W| S)zkReturns a new instance of the :class:`Dataset`,
        including only specified rows and columns.
        Nc                s+   g  |  ]! } | t    j  k r |  q Sr   )rangerL   )r   r   )r   r   r   rN      s   	 z"Dataset.subset.<locals>.<listcomp>c                s%   g  |  ] } |   j  k r |  q Sr   )rB   )r   r   )r   r   r   rN     s   	 r   )r   r   rL   rB   r@   rD   rS   r1   r0   rP   r	   )	r   r   colsr   Zrow_nor   ro   rQ   rM   r   )r   r   subset  s*    		
zDataset.subset)Ar;   r<   r=   r>   rh   r   r   r   r   r    r   rc   rd   classmethodrI   rR   rw   rx   rz   r?   rB   r{   r   r!   r   rL   rk   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r-   r.   r/   r0   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@   n   sv   -%					
>

'"r@   c               @   s   e  Z d  Z d Z i  Z d d d  Z d d   Z d d   Z e d	 d
    Z	 d d   Z
 d d   Z d d d  Z e d d    Z d d   Z d d   Z d S)Databookz(A book of :class:`Dataset` objects.
    Nc             C   s2   | d  k r t    |  _ n	 | |  _ |  j   d  S)N)r   	_datasetsrI   )r   Zsetsr   r   r   r     s    	zDatabook.__init__c             C   s2   y d |  j  j   SWn t k
 r- d SYn Xd  S)Nz<%s databook>z<databook object>)rC   rT   rU   )r   r   r   r   r   (  s    zDatabook.__repr__c             C   s   g  |  _  d S)z@Removes all :class:`Dataset` objects from the :class:`Databook`.N)r   )r   r   r   r   r|   .  s    zDatabook.wipec             C   s   x t  j D] } y yB t |  | j t | j | j   | j | j f |  j | j <WnG t k
 r t |  | j t | j   | j d f |  j | j <Yn XWq
 t k
 r d |  j | j <Yq
 Xq
 Wd S)zAdds format properties.N)NN)	r   re   r(   rC   r?   export_bookimport_bookrh   rU   )ri   rj   r   r   r   rI   3  s    " "zDatabook._register_formatsc             C   s   |  j  S)N)r   )r   r   r   r   sheetsB  s    zDatabook.sheetsc             C   s,   t  | t  r" |  j j |  n t  d S)z5Adds given :class:`Dataset` to the :class:`Databook`.N)r5   r@   r   r0   InvalidDatasetType)r   Zdatasetr   r   r   	add_sheetE  s    zDatabook.add_sheetTc          	   C   s^   g  } | r t  } n t } x< |  j D]1 } | j | d | j d | j d |    q% W| S)z(Packages :class:`Databook` for delivery.rC   rv   rs   )r   r!   r   r0   rC   rw   )r   rs   Z	collectorrp   Zdsetr   r   r   rw   M  s    		zDatabook._packagec             C   s   t  |  j  S)zDThe number of the :class:`Dataset` objects within :class:`Databook`.)r   r   )r   r   r   r   size^  s    zDatabook.sizec             K   sb   | s t  |  } n  |  j j | d  \ } } | sN t d j |    n  | |  | |  |  S)z
        Import `in_stream` to the :class:`Databook` object using the `format`.

        :param \*\*kwargs: (optional) custom configuration to the format `import_book`.
        NzFormat {0} cannot be loaded.)NN)r   rh   rH   r   r]   )r   r]   r   rK   r   r   r   r   r   r   c  s    zDatabook.loadc             K   sF   |  j  j | d  \ } } | s9 t d j |    n  | |  |  S)z
        Export :class:`Databook` object to `format`.

        :param \*\*kwargs: (optional) custom configuration to the format `export_book`.
        NzFormat {0} cannot be exported.)NN)rh   rH   r   r]   )r   r]   rK   r   r   r   r   r   r   t  s    zDatabook.export)r;   r<   r=   r>   rh   r   r   r|   r   rI   r   r   rw   r?   r   r   r   r   r   r   r   r     s   	r   c             C   sG   x@ t  j D]5 } y | j |   r) | j SWq
 t k
 r> Yq
 Xq
 Wd S)z#Return format name of given stream.N)r   re   ZdetectrC   rU   )streamrj   r   r   r   r     s    r   Nc             K   s   t    j |  | |  S)zReturn dataset of given stream.)r@   r   )r   r]   rK   r   r   r   rg     s    rg   c             K   s   t    j |  | |  S)zReturn dataset of given stream.)r   r   )r   r]   rK   r   r   r   r     s    r   c               @   s   e  Z d  Z d Z d S)r   z(Only Datasets can be added to a DataBookN)r;   r<   r=   r>   r   r   r   r   r     s   r   c               @   s   e  Z d  Z d Z d S)rn   zInvalid sizeN)r;   r<   r=   r>   r   r   r   r   rn     s   rn   c               @   s   e  Z d  Z d Z d S)rr   zOutside of Dataset sizeN)r;   r<   r=   r>   r   r   r   r   rr     s   rr   c               @   s   e  Z d  Z d Z d S)r   zGHeader parameter must be given when appending a column in this Dataset.N)r;   r<   r=   r>   r   r   r   r   r     s   r   c               @   s   e  Z d  Z d Z d S)r   zFormat is not supportedN)r;   r<   r=   r>   r   r   r   r   r     s   r   )r>   r   operatorr   r   r   Ztablib.compatr   r   Z	__title____version__Z	__build__
__author__Z__license____copyright__Z__docformat__objectr	   r@   r   r   rg   r   	Exceptionr   rn   rr   r   NotImplementedErrorr   r   r   r   r   <module>
   s2   Q   h	