o
    5ti                     @   s  U d 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	m
Z
mZmZ ddlZddlmZmZmZmZmZmZmZ ddlmZ ddlmZmZmZ ddlmZmZ d	d
lmZ d	dl m!Z!m"Z"m#Z#m$Z$ d	dl%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z- d	dl.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 erddl7Z7ddl8Z8d	dl9m:Z: e,j;ej;e,j<ej=e,j>ej=e,j?ej=iZ@eAe,eBf eCd< de&de	de
e) fddZDeDgZEeFe* eCd< G dd de4ejGdZHdS )zA
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
    N)Sequence)TYPE_CHECKINGAnyOptionalUnioncast)AlignColumnDataPropertyDataPropertyDataPropertyExtractorFormatMatrixFormattingPreprocessor)	TransFunc)	TableDataconvert_idx_to_alphabetto_value_matrix)Typecodeextract_typepy_from_dtype   )WriterLogger)EmptyTableDataErrorEmptyTableNameErrorEmptyValueErrorNotSupportedError)CellCheckStyleFilterKeywordArgsFuncColSeparatorStyleFilterFuncStyleStyleFilterFuncStylerInterfaceThousandSeparatorfetch_theme)IntegerTypeHint   )
HEADER_ROW)TableWriterInterface)to_error_messageTableFormat_ts_to_flagcellkwargsreturnc                 K   s   |   r
ttjdS d S )N)align)is_header_rowr   r   CENTER)r,   r-    r2   V/home/ubuntu/.local/lib/python3.10/site-packages/pytablewriter/writer/_table_writer.pyheader_style_filter:   s   r4   DEFAULT_STYLE_FILTERSc                
   @   s&  e Zd ZdZdZedefddZejdeddfddZede	fd	d
Z
e
jde	ddfdd
Z
edddZedefddZejdeddfddZejdeddfddZdeddfddZdefddZedefddZdddZdddZede	e fd d!Zejde	e ddfd"d!Zedefd#d$Zejdeddfd%d$Zedefd&d'Zejdeddfd(d'Zedefd)d*Zedefd+d,Zejdeddfd-d,Zedee  fd.d/Z!e!jde	e"ee f  ddfd0d/Z!ede#fd1d2Z$e$jd3e%e# ddfd4d2Z$edee%e#  fd5d6Z&e&jde	e%e#  ddfd7d6Z&edefd8d9Z'e'jdeddfd:d9Z'edefd;d<Z(e(jdeddfd=d<Z(ede)e*ef fd>d?Z+e+jde)e*ef ddfd@d?Z+dAe,ddfdBdCZ-dAe.ddfdDdEZ/ddFdGZ0ddHdIZ1ddKeddfdLdMZ2dNe"eef d3e#ddfdOdPZ3dQededdfdRdSZ4defdTdUZ5ddVdWZ6ddedYeddfdZd[Z7dd]ed^eddfd_d`Z8	J	XddadbdceddeddfdedfZ9ddgdhdceddfdidjZ:ddmdnZ;	Xddod dYeddfdpdqZ<dre=ddfdsdtZ>deddfdudvZ?deddfdwdxZ@deddfdydzZA	dd{eBd|e%eC defd}d~ZDdeBd|eCdefddZEdeBd|eCd3e#defddZFdedeBd|eCdefddZGdedeBd|eCd3e#def
ddZHdedeBd|eCde#de#f
ddZIdede#fddZJdedeKdeKfddZLdeBd|eCdeKfddZMdddZNde	ddfddZOde	e"ee f  ddfddZPdddZQdddZRdddZSdddZTdddZUdddZVdod deWfddZXdddZYdedeBd|eCde#fddZZdddZ[dddZ\dddZ]dddZ^dddZ_dddZ`dS )AbstractTableWritera/	  
    An abstract base class of table writer classes.

    Args:
        max_precision (int): Maximum decimal places for real number values.

        dequote (bool): If |True|, dequote values in :py:attr:`~.value_matrix`.

    .. py:attribute:: stream

        Stream to write tables.
        You can use arbitrary streams which support ``write``methods
        such as ``sys.stdout``, file stream, ``StringIO``, and so forth.
        Defaults to ``sys.stdout``.

        :Example:
            :ref:`example-configure-stream`

    .. py:attribute:: is_write_header
        :type: bool

        Write headers of a table if the value is |True|.

    .. py:attribute:: is_padding
        :type: bool

        Padding for each item in the table if the value is |True|.

    .. py:attribute:: iteration_length
        :type: int

        The number of iterations to write a table.
        This value is used in :py:meth:`.write_table_iter` method.
        (defaults to ``-1``, which means the number of iterations is indefinite)

    .. py:attribute:: style_filter_kwargs
        :type: Dict[str, Any]

        Extra keyword arguments for style filter functions.
        These arguments will pass to filter functions added by
        :py:meth:`.add_style_filter` or :py:meth:`.add_col_separator_style_filter`

    .. py:attribute:: colorize_terminal
        :type: bool
        :value: True

        [Only available for text format writers] [experimental]
        If |True|, colorize text outputs with |Style|.

    .. py:attribute:: enable_ansi_escape
        :type: bool
        :value: True

        [Only available for text format writers]
        If |True|, applies ANSI escape sequences to the terminal's text outputs with |Style|.

    .. py:attribute:: write_callback

        The value expected to a function.
        The function is called when each of the iterations of writing a table
        completed. (defaults to |None|)
        For example, a callback function definition is as follows:

        .. code:: python

            def callback_example(iter_count: int, iter_length: int) -> None:
                print("{:d}/{:d}".format(iter_count, iter_length))

        Arguments that passed to the callback are:

        - first argument: current iteration number (start from ``1``)
        - second argument: a total number of iteration
    abstractr.   c                 C      t  NNotImplementedErrorselfr2   r2   r3   margin      zAbstractTableWriter.marginvalueNc                 C   r8   r9   r:   r=   r@   r2   r2   r3   r>      r?   c                 C      | j S )z Data of a table to be outputted.&_AbstractTableWriter__value_matrix_orgr<   r2   r2   r3   value_matrix      z AbstractTableWriter.value_matrixrE   c                 C   s   |  | |   d S r9   )&_AbstractTableWriter__set_value_matrix&_AbstractTableWriter__clear_preprocessr=   rE   r2   r2   r3   rE      s   
r*   c                 C   s$   ddl m} || j}|sJ |S )z*TableFormat: Get the format of the writer.r   r)   )_table_formatr*   	from_nameformat_name)r=   r*   table_formatr2   r2   r3   rM      s   z AbstractTableWriter.table_formatc                 C   rB   r9   _streamr<   r2   r2   r3   stream   r?   zAbstractTableWriter.streamc                 C   
   || _ d S r9   rN   rA   r2   r2   r3   rP         
r-   c                 K      d S r9   r2   r=   r-   r2   r2   r3   _write_table   s   z AbstractTableWriter._write_tablec                 K   s6  t | | _|dd| _|dg | _|dd| _|dd| _|dd| _|d	d| _|d
d| _	d| _
t|dd| _d| j_d| j_t|ddd| j_| jtjd tj| j_| jtjdi |dd| _|dd| _|dg | _|dg | _tjdtjdtjdtjdtj dtj!dtj"dtj#dtjdtj$dtj%dtj&di| _'d| _(d| _)|dd| _*|ddd | _+d | _,|  |dt- | _.g | _/|dg | _0t12t3| _4d| _5| 6| | _7|di | _8g | _9|dd| _:|dd| _;|dd| _<d |v r| =|d   | >  d S )!N
table_name rE   is_write_headerTis_write_header_separator_rowis_write_value_separator_rowFis_write_opening_rowis_write_closing_rowmax_precision)r]   r%   "dequote)r_   is_formatting_float
is_paddingheaders
type_hintsiteration_lengthwrite_callbackc                 S   rS   r9   r2   )_iter_count_iter_lengthr2   r2   r3   <lambda>   s    z.AbstractTableWriter.__init__.<locals>.<lambda>default_stylecolumn_stylesstyle_filter_kwargscolorize_terminalenable_ansi_escapemax_workers	dataframe)?r   _loggergetrV   rE   rX   rY   rZ   r[   r\   _use_default_headerr   _dp_extractormin_column_widthstrip_str_headerr   preprocessorset_type_valuer   NONEr   HEADER_ALIGNEDmatrix_formattingupdate_strict_level_mapBOOLr`   ra   rb   rc   DATETIME
DICTIONARYINFINITYINTEGER
IP_ADDRESSLISTNANNULL_STRINGREAL_NUMBERSTRING_quoting_flags_is_require_table_name_is_require_headerrd   rf   rg   r   rj   $_AbstractTableWriter__col_style_listrk   copydeepcopyr5   _style_filters_enable_style_filter_create_styler_stylerrl    _check_style_filter_kwargs_funcs'_AbstractTableWriter__colorize_terminal(_AbstractTableWriter__enable_ansi_escapero   from_dataframerH   rT   r2   r2   r3   __init__   sp   


zAbstractTableWriter.__init__c                 C   s<   ddl m} || j| j| j| j| j| jd}| j|_|	 S )Nr%   )HtmlTableWriter)rV   rb   rE   rk   rm   rn   )

text._htmlr   rV   rb   rE   rk   rm   rn   rt   dumps)r=   r   writerr2   r2   r3   _repr_html_  s   zAbstractTableWriter._repr_html_c                 C      | j jS r9   )rt   rw   r<   r2   r2   r3   value_preprocessor     z&AbstractTableWriter.value_preprocessorc                 C   s   d| _ d| _d| _d| _d S )NF) _is_complete_table_dp_preprocess&_is_complete_table_property_preprocess_is_complete_header_preprocess$_is_complete_value_matrix_preprocessr<   r2   r2   r3   __clear_preprocess_status     
z-AbstractTableWriter.__clear_preprocess_statusc                 C   s   g | _ g | _g | _g | _d S r9   )_column_dp_list_table_headers_table_value_matrix_table_value_dp_matrixr<   r2   r2   r3   __clear_preprocess_data  r   z+AbstractTableWriter.__clear_preprocess_datac                 C   r   )z2Sequence[str]: Headers of a table to be outputted.rt   rb   r<   r2   r2   r3   rb   #  s   zAbstractTableWriter.headersc                 C      || j _d S r9   r   rA   r2   r2   r3   rb   )     c                 C   r   r9   )rt   r`   r<   r2   r2   r3   r`   -  r   z'AbstractTableWriter.is_formatting_floatc                 C   s$   | j j|krd S || j _|   d S r9   )rt   r`   rH   rA   r2   r2   r3   r`   1  s   c                 C   r   r9   rt   ro   r<   r2   r2   r3   ro   9  r   zAbstractTableWriter.max_workersc                 C   r   r9   r   rA   r2   r2   r3   ro   =  r   c                 C   s   t | j| j| j| j| jjdS )z4tabledata.TableData: Get tabular data of the writer.)ro   r]   )r   rV   rb   rE   ro   rt   r]   r<   r2   r2   r3   	tabledataA  s   zAbstractTableWriter.tabledatac                 C   rB   )zstr: Name of a table._table_namer<   r2   r2   r3   rV   M  rF   zAbstractTableWriter.table_namec                 C   rQ   r9   r   rA   r2   r2   r3   rV   S  rR   c                 C   r   )a
  
        Type hints for each column of the tabular data.
        Writers convert data for each column using the type hints information
        before writing tables when you call ``write_xxx`` methods.

        Acceptable values are as follows:

            - |None| (automatically detect column type from values in the column)
            - :py:class:`pytablewriter.typehint.Bool` or ``"bool"``
            - :py:class:`pytablewriter.typehint.DateTime` or ``"datetime"``
            - :py:class:`pytablewriter.typehint.Dictionary` or ``"dict"``
            - :py:class:`pytablewriter.typehint.Infinity` or ``"inf"``
            - :py:class:`pytablewriter.typehint.Integer` or ``"int"``
            - :py:class:`pytablewriter.typehint.IpAddress` or ``"ipaddr"``
            - :py:class:`pytablewriter.typehint.List` or ``"list"``
            - :py:class:`pytablewriter.typehint.Nan` or ``"nan"``
            - :py:class:`pytablewriter.typehint.NoneType` or ``"none"``
            - :py:class:`pytablewriter.typehint.NullString` or ``"nullstr"``
            - :py:class:`pytablewriter.typehint.RealNumber` or ``"realnumber"`` or ``"float"``
            - :py:class:`pytablewriter.typehint.String` or ``"str"``

        If a type-hint value is not |None|, the writer tries to
        convert data for each data in a column to type-hint class.
        If the type-hint value is |None| or failed to convert data,
        the writer automatically detects column data type from
        the column data.

        If ``type_hints`` is |None|, the writer automatically detects data types
        for all of the columns and writes a table using detected column types.

        Defaults to |None|.

        Examples:
            - :ref:`example-type-hint-js`
            - :ref:`example-type-hint-python`
        rt   column_type_hintsr<   r2   r2   r3   rc   W  s   'zAbstractTableWriter.type_hintsc                 C   s,   t |}| j|krd S | | |   d S r9   )listrc   $_AbstractTableWriter__set_type_hintsrH   )r=   r@   hintsr2   r2   r3   rc     s
   

c                 C   rB   )z&Style: Default |Style| of table cells.)#_AbstractTableWriter__default_styler<   r2   r2   r3   rj     rF   z!AbstractTableWriter.default_stylestylec                 C   sj   |d u rt  }t|t stdz
| j|krW d S W n	 ty#   Y nw || _t| jj | j_| 	  d S )Nz&default_style must be a Style instance)
r   
isinstance	TypeErrorr   AttributeErrorr+   thousand_separatorrt   default_format_flagsrH   )r=   r   r2   r2   r3   rj     s    

c                 C   rB   )z/List[Optional[Style]]: |Style| for each column.)r   r<   r2   r2   r3   rk     rF   z!AbstractTableWriter.column_stylesc                    sT    j |krd S t| _  j r  fddtt j D  j_ng  j_   d S )Nc                       g | ]
}t  |j qS r2   r+   _get_col_styler   .0col_idxr<   r2   r3   
<listcomp>      z5AbstractTableWriter.column_styles.<locals>.<listcomp>)r   r   rangelenrt   format_flags_listrH   rA   r2   r<   r3   rk     s   


c                 C   rB   r9   )r   r<   r2   r2   r3   rm     r?   z%AbstractTableWriter.colorize_terminalc                 C       | j |krd S || _ |   d S r9   )r   rH   rA   r2   r2   r3   rm        
c                 C   rB   r9   )r   r<   r2   r2   r3   rn     r?   z&AbstractTableWriter.enable_ansi_escapec                 C   r   r9   )r   rH   rA   r2   r2   r3   rn     r   c                 C   r   r9   )rt   quoting_flagsr<   r2   r2   r3   r     r   z"AbstractTableWriter._quoting_flagsc                 C   s   || j _|   d S r9   )rt   r   rH   rA   r2   r2   r3   r     s   style_filterc                 C   s   | j d| |   dS )aG  Add a style filter function to the writer.

        Args:
            style_filter:
                A function called for each table cell to apply a style to table cells.
                The function will be required to implement the following Protocol:

                .. code-block:: python

                    class StyleFilterFunc(Protocol):
                        def __call__(self, cell: Cell, **kwargs: Any) -> Optional[Style]:
                            ...

                If more than one style filter function is added to the writer,
                it will be called from the last one added.
                These style functions should return |None| when not needed to apply styles.
                If all of the style functions returned |None|,
                :py:attr:`~.default_style` will be used.

                You can pass keyword arguments to style filter functions via
                :py:attr:`~.style_filter_kwargs`. In default, the attribute includes:

                    - ``writer``: the writer instance that the caller of a ``style_filter function``
        r   N)r   insertrH   r=   r   r2   r2   r3   add_style_filter  s   z$AbstractTableWriter.add_style_filterc                 C   s   | j jd d S )NzWadd_col_separator_style_filter method is only implemented in text format writer classes)rq   loggerdebugr   r2   r2   r3   add_col_separator_style_filter  s   z2AbstractTableWriter.add_col_separator_style_filterc                 C   s(   | j sdS tt| _ g | _|   dS )z Remove all of the style filters.N)r   r   r   r5   r   rH   r<   r2   r2   r3   clear_theme  s
   zAbstractTableWriter.clear_themec                 C   s    | j du rdS d| _ |   dS )zEnable style filters.TN)r   rH   r<   r2   r2   r3   enable_style_filter  s   
z'AbstractTableWriter.enable_style_filterFclear_filtersc                 C   s0   |r|    dS | jdu rdS d| _|   dS )zDisable style filters.

        Args:
            clear_filters (bool):
                If |True|, clear all of the style filters.
                Defaults to |False|.
        NF)r   r   rH   )r=   r   r2   r2   r3   disable_style_filter  s   	
z(AbstractTableWriter.disable_style_filtercolumnc                    s   d}t  jt  jkr jd t  jt  jkst|tr$|}nt|tr;z j|}W n	 ty:   Y nw |durZ| j|<  	   fddt
t  jD  j_dS td| )aa  Set |Style| for a specific column.

        Args:
            column (|int| or |str|):
                Column specifier. Column index or header name correlated with the column.
            style (|Style|):
                Style value to be set to the column.

        Raises:
            ValueError: Raised when the column specifier is invalid.
        Nc                    r   r2   r   r   r<   r2   r3   r   A  r   z1AbstractTableWriter.set_style.<locals>.<listcomp>z(column must be an int or string: actual=)r   rb   r   appendr   intstrindex
ValueErrorrH   r   rt   r   )r=   r   r   
column_idxr2   r<   r3   	set_style$  s(   




zAbstractTableWriter.set_stylethemec              
   K   s   zt | }W n ty" } zt| t W Y d}~dS d}~ww |jr,| |j |jr5| 	|j |j
r?| j|j
 | jjdi | dS )a(  Set style filters for a theme.

        Args:
            theme (str):
                Name of the theme. pytablewriter theme plugin must be installed
                corresponding to the theme name.

        Raises:
            RuntimeError: Raised when a theme plugin does not install.
        Nr2   )r"   stripRuntimeErrorwarningswarnUserWarningr   r   col_separator_style_filterr   check_style_filter_kwargsr   r   rl   update)r=   r   r-   fetched_themeer2   r2   r3   	set_themeI  s   zAbstractTableWriter.set_themec                 C   s   zddl m} t| j|rW dS W n	 ty   Y nw zddl m} t| j|r+W dS W n% tyQ   zddlm} t| j|rDW Y dS W n	 tyN   Y nw Y nw zddlm} t| j|rbW dS W dS  tyn   Y dS w )Nr   )EncodedFileT)	CaptureIO)	OutStreamF)	_pytest.capturer   r   rP   ImportErrorr   _pytest.compatipykernel.iostreamr   )r=   r   r   r   r2   r2   r3   __is_skip_closef  sD   z#AbstractTableWriter.__is_skip_closec                 C   s   | j du rdS z| j   | j jdv rW dS W n ty    Y n	 ty(   Y nw |  r/dS z*z| j   W n tyM   | jj	dt
| j   Y nw W d| _dS W d| _dS d| _w )z-
        Close the current |stream|.
        N)z<stdin>z<stdout>z<stderr>z4the stream has no close method implementation: type=)rP   isattynamer   r   #_AbstractTableWriter__is_skip_closecloserq   r   warningtyperO   r<   r2   r2   r3   r     s2   


zAbstractTableWriter.closeTis_overwrite_table_namec                 C   sx   |    |r|jr|jnd| _|j| _t|j| _|jsdS |j| _| j	
| j| j| _| dd | jD  d| _dS )a  
        Set tabular attributes to the writer from |TableData|.
        The following attributes are configured:

        - :py:attr:`~.table_name`.
        - :py:attr:`~.headers`.
        - :py:attr:`~.value_matrix`.

        |TableData| can be created from various data formats by
        ``pytablereader``. More detailed information can be found in
        https://pytablereader.rtfd.io/en/latest/

        :param tabledata.TableData value: Input table data.
        rW   Nc                 S   s   g | ]}|j qS r2   )
type_class)r   col_dpr2   r2   r3   r         z6AbstractTableWriter.from_tabledata.<locals>.<listcomp>T)rH   rV   rb   r   rowsrE   has_value_dp_matrixvalue_dp_matrixr   rt   to_column_dp_listr   r   r   )r=   r@   r   r2   r2   r3   from_tabledata  s   
z"AbstractTableWriter.from_tabledata,
csv_source	delimiterc                 C   s   ddl }|j|| jd}||_z| D ]	}| j|dd qW dS  |jy*   Y nw |j|| jd}||_| D ]}| | q:dS )a2  
        Set tabular attributes to the writer from a character-separated values (CSV) data source.
        The following attributes are set to the writer by the method:

        - :py:attr:`~.headers`.
        - :py:attr:`~.value_matrix`.

        :py:attr:`~.table_name` also be set if the CSV data source is a file.
        In that case, :py:attr:`~.table_name` is as same as the filename.

        Args:
            csv_source (str):
                Input CSV data source can be designated CSV text or a CSV file path.

            delimiter (str):
                Delimiter character of the CSV data source.
                Defaults to ``,``.

        Examples:
            :ref:`example-from-csv`

        :Dependency Packages:
            - `pytablereader <https://github.com/thombashi/pytablereader>`__
        r   N)r   F)r   )pytablereaderCsvTableTextLoaderr   r  loadr   	DataErrorCsvTableFileLoader)r=   r  r  ptrloader
table_datar2   r2   r3   from_csv  s   zAbstractTableWriter.from_csvrp   zpandas.DataFrameadd_index_columnoverwrite_type_hintsc                 C   s   t |trddl}||}n|}t|jj| _| jr|r&dd |j	D | _|rX|j
jr2t|j
jnd}|g| j | _| jrEtg| j | _dd t|j
 |j D | _dS |j | _dS )a  
        Set tabular attributes to the writer from :py:class:`pandas.DataFrame`.
        The following attributes are set by the method:

            - :py:attr:`~.headers`
            - :py:attr:`~.value_matrix`
            - :py:attr:`~.type_hints`

        Args:
            dataframe(pandas.DataFrame or |str|):
                Input pandas.DataFrame object or path to a DataFrame pickle.
            add_index_column(bool, optional):
                If |True|, add a column of ``index`` of the ``dataframe``.
                Defaults to |False|.
            overwrite_type_hints(bool):
                If |True|, Overwrite type hints with dtypes within the DataFrame.

        Example:
            :ref:`example-from-pandas-dataframe`
        r   Nc                 S      g | ]}t |qS r2   )r   )r   dtyper2   r2   r3   r     s    z6AbstractTableWriter.from_dataframe.<locals>.<listcomp> c                 S   s   g | ]\}}|gt | qS r2   )r   )r   r   rowr2   r2   r3   r   $  s    )r   r   pandasread_pickler   columnsvaluesrb   rc   dtypesr   r   r#   ziptolistrE   )r=   rp   r  r  pddfindex_headerr2   r2   r3   r     s    

z"AbstractTableWriter.from_dataframeserieszpandas.Seriesc                 C   s   |j rt|j g| _ndg| _t|jg| _|r;dg| j | _| jr)dg| j | _dd t|j | D | _	dS dd | D | _	dS )a  
        Set tabular attributes to the writer from :py:class:`pandas.Series`.
        The following attributes are set by the method:

            - :py:attr:`~.headers`
            - :py:attr:`~.value_matrix`
            - :py:attr:`~.type_hints`

        Args:
            series(pandas.Series):
                Input pandas.Series object.
            add_index_column(bool, optional):
                If |True|, add a column of ``index`` of the ``series``.
                Defaults to |True|.
        r@   rW   Nc                 S   s   g | ]
\}}|g|g qS r2   r2   )r   r   r@   r2   r2   r3   r   F  s    z3AbstractTableWriter.from_series.<locals>.<listcomp>c                 S   s   g | ]}|gqS r2   r2   )r   r@   r2   r2   r3   r   J  r   )
r   r   rb   r   r  rc   r  r   r  rE   )r=   r  r  r2   r2   r3   from_series*  s   zAbstractTableWriter.from_seriestablib_datasettablib.Datasetc                 C   s"   |j r|j | _ dd |D | _dS )zW
        Set tabular attributes to the writer from :py:class:`tablib.Dataset`.
        c                 S   s   g | ]}|qS r2   r2   )r   r  r2   r2   r3   r   S  s    z3AbstractTableWriter.from_tablib.<locals>.<listcomp>N)rb   rE   )r=   r  r2   r2   r3   from_tablibL  s   zAbstractTableWriter.from_tablibr   c                 C   s   |    |rt|j| _|j| _|j| _|j| _|j| _|j| _|j| _|j	| _	|j
| _
|j| _|j| _|j| _|j| _|j| _|j| _|j| _|j| _dS )a  
        Copy attributes from another table writer class instance.

        Args:
            writer (pytablewriter.writer.AbstractTableWriter):
                Another table writer instance.
            is_overwrite_table_name (bool, optional):
                Overwrite the table name of the writer with the table name of the ``writer``.
                Defaults to |True|.
        N)rH   r   rV   rb   rE   rc   rk   r   rl   r>   r   r   r   r   rP   r   r   r   r   )r=   r   r   r2   r2   r3   from_writerU  s&   zAbstractTableWriter.from_writer
trans_funcc                 C   s   | j | |   d S r9   )rt   register_trans_funcrH   )r=   r#  r2   r2   r3   r$  }  s   z'AbstractTableWriter.register_trans_funcc                 K   s"   | j jdi |sd S |   d S Nr2   )rt   update_preprocessorrH   rT   r2   r2   r3   r&    s   z'AbstractTableWriter.update_preprocessorc              	   K   sx   | j / z|   W n ty!   | j jd Y W d   dS w | jdi | W d   dS 1 s5w   Y  dS )z 
        |write_table|.
        no tabular data foundNr2   )rq   _verify_propertyr   r   r   rU   rT   r2   r2   r3   write_table  s   "zAbstractTableWriter.write_tablec              	   K   s  | j std|   |   |   tt| jt| j	gr*| j
jd d S |   | j
jd| jd | j}| j}| j}zd| _d| _| j	D ]X}t| jdk| j| jkg}|rad| _| | |   | j
 | jd	i | |s||   W d    n1 sw   Y  d| _d| _| | j| j 	 |r n|  jd7  _qMW || _|| _|| _d | _d S W || _|| _|| _d | _d S || _|| _|| _d | _w )
Nz3the class not supported the write_table_iter methodr'  z$_write_table_iter: iteration-length=dFr%   r   Tr2   )support_split_writer   _verify_style_filter_kwargs_verify_table_name_verify_streamalltypepyis_empty_sequencerb   rE   rq   r   r   _verify_headerrd   rX   r[   r\   rg   rG   -_AbstractTableWriter__clear_preprocess_statusrU   _write_value_row_separatorrf   )r=   r-   stash_is_write_headerstach_is_write_opening_rowstash_is_write_closing_rowwork_matrixis_final_iterr2   r2   r3   _write_table_iter  sj   

#

z%AbstractTableWriter._write_table_iter	column_dpvalue_dpc                 C   s8   | j sdS z
tt||jW S  ty   |j Y S w )Nr   )ra   r   r
   get_padding_lenascii_char_widthr   )r=   r;  r<  r2   r2   r3   _get_padding_len  s   
z$AbstractTableWriter._get_padding_lenr   c                 C   s0   |  t||}| |||}| jj||d}|S N)r   )_fetch_styler&   _apply_style_to_header_itemr   apply_terminal_style)r=   r   r<  r   headerr2   r2   r3   _to_header_item  s   z#AbstractTableWriter._to_header_itemc                 C   s"   | j j| j j|||d|dS r@  r   apply_alignapply	dp_to_str)r=   r   r<  r   r2   r2   r3   rB       z/AbstractTableWriter._apply_style_to_header_itemrow_idxc                 C   s.   |  |||}| ||||}| jj||dS r@  )rA  _apply_style_to_row_itemr   rC  )r=   rK  r   r<  r   r@   r2   r2   r3   _to_row_item  s   z AbstractTableWriter._to_row_itemc                 C   s"   | j j| j j|||d|dS r@  rF  )r=   rK  r   r<  r   r2   r2   r3   rL    rJ  z,AbstractTableWriter._apply_style_to_row_itemrj   c                 C   s   | j s|S | jd| i d }| jD ]}|t||j|j|dfi | j}|r) nq|d u r3t|}|j	d u sB|j	t
jkrI|dkrI| |||_	|jd u rU| |||_|S )Nr   )r  colr@   rj   r   )r   rl   r   r   r   column_indexdatar   r   r/   r   AUTO._AbstractTableWriter__retrieve_align_from_datapaddingr?  )r=   rK  r   r<  rj   r   r   r2   r2   r3   _fetch_style_from_filter   s2   
	

z,AbstractTableWriter._fetch_style_from_filterr   c              
   C   s:   z| j | }W n tttfy   Y | jS w |r|S | jS r9   )rk   r   
IndexErrorKeyErrorrj   )r=   r   r   r2   r2   r3   r   !  s   z"AbstractTableWriter._get_col_styledefault_alignc                 C   s*   |  |j}|d u r|S |tjkr|S |S r9   )r   r/   r   rQ  )r=   r   rW  r/   r2   r2   r3   
_get_align,  s   
zAbstractTableWriter._get_alignc                 C   s<   |j tjkr|j tjtjfv s|j tjkr|jr|jS |jS r9   )typecoder   r   r   r   is_include_ansi_escaper/   )r=   r   r<  r2   r2   r3   __retrieve_align_from_data7  s   z.AbstractTableWriter.__retrieve_align_from_datac                 C   sp   |    |   |   tt| jt| jt| jgr"t	 | 
  z|   W d S  ty7   Y d S w r9   )r,  r-  r.  r/  r0  r1  rb   rE   r   r   r2  _verify_value_matrixr   r<   r2   r2   r3   r(  C  s    


z$AbstractTableWriter._verify_propertyc                 C   rQ   r9   rC   rI   r2   r2   r3   __set_value_matrixW  s   
z&AbstractTableWriter.__set_value_matrixrc   c                 C   r   r9   r   )r=   rc   r2   r2   r3   __set_type_hintsZ     z$AbstractTableWriter.__set_type_hintsc                 C   s    | j D ]
}|di | j qd S r%  )r   rl   )r=   checkerr2   r2   r3   r,  ]  s   
z/AbstractTableWriter._verify_style_filter_kwargsc                 C   s"   t | jt| jgrtdd S )NzAtable_name must be a string, with at least one or more character.)r/  r   r0  is_null_stringrV   r   r<   r2   r2   r3   r-  a  s
   z&AbstractTableWriter._verify_table_namec                 C   s   | j d u r	tdd S )Nznull output stream)rP   OSErrorr<   r2   r2   r3   r.  g  s   
z"AbstractTableWriter._verify_streamc                 C   s    | j r| js|   d S d S d S r9   )r   rs   _validate_empty_headerr<   r2   r2   r3   r2  k  s   z"AbstractTableWriter._verify_headerc                 C   s   t | jr
tddS )zL
        Raises:
            ValueError: If the |headers| is empty.
        z1headers expected to have one or more header namesN)r0  r1  rb   r   r<   r2   r2   r3   rc  o  s   z*AbstractTableWriter._validate_empty_headerc                 C   s   t | jr	t d S r9   )r0  r1  rE   r   r<   r2   r2   r3   r\  x  s   z(AbstractTableWriter._verify_value_matrixc                 C   s   ddl m} ||S )Nr   )
NullStyler)style._stylerrd  )r=   r   rd  r2   r2   r3   r   |  s   z"AbstractTableWriter._create_stylerc              
   C   s   | j rd S | jjd t| jr$| jr$dd tt	| j
d D | _z| jt| j| j
| _W n tyP } z| jjt| g | _W Y d }~nd }~ww | j| j| j| _d| _ d S )N_preprocess_table_dpc                 S   r  r2   )r   r   r2   r2   r3   r     s    z<AbstractTableWriter._preprocess_table_dp.<locals>.<listcomp>r   T)r   rq   r   r   r0  r1  rb   rs   r   r   rD   rt   to_dp_matrixr   r   r   r(   r   r   )r=   r   r2   r2   r3   rf    s(   

z(AbstractTableWriter._preprocess_table_dpr  c                 C   s   |  |j}| ||||S r9   )r   rO  rT  )r=   r  r   r<  rj   r2   r2   r3   rA    s   z AbstractTableWriter._fetch_stylec                 C   s   | j rd S | jjd | jdkr$| jD ]}|tt	|j
d  q| j }|s-d S | jD ]&}| |j}| t|||j }| j|}| j|}|t|| q0d| _ d S )N_preprocess_table_propertyr%   g      ?T)r   rq   r   r   rg   r   extend_widthr   mathceilr>  rt   to_header_dp_listr   rO  rA  r&   r   get_additional_char_widthextend_body_widthmax)r=   r;  header_dp_listr   header_style
body_widthheader_widthr2   r2   r3   rh    s$   




z.AbstractTableWriter._preprocess_table_propertyc                    sD    j rd S  jjd  fddt j j D  _d _ d S )N_preprocess_headerc                    s   g | ]
\}}  ||qS r2   )rE  )r   r   	header_dpr<   r2   r3   r     s    
z:AbstractTableWriter._preprocess_header.<locals>.<listcomp>T)	r   rq   r   r   r  r   rt   rl  r   r<   r2   r<   r3   rt    s   

z&AbstractTableWriter._preprocess_headerc                    sH    j rd S  jjdt j   fddt jD  _d _ d S )Nz%_preprocess_value_matrix: value-rows=c                    s,   g | ]\ } fd dt j|D qS )c                    s   g | ]\}}  ||qS r2   )rM  )r   r   r<  )rK  r=   r2   r3   r     s    zKAbstractTableWriter._preprocess_value_matrix.<locals>.<listcomp>.<listcomp>)r  r   )r   value_dp_listr<   )rK  r3   r     s    
z@AbstractTableWriter._preprocess_value_matrix.<locals>.<listcomp>T)r   rq   r   r   r   r   	enumerater   r<   r2   r<   r3   _preprocess_value_matrix  s   

z,AbstractTableWriter._preprocess_value_matrixc                 C   s$   |    |   |   |   d S r9   )rf  rh  rt  rx  r<   r2   r2   r3   _preprocess  s   zAbstractTableWriter._preprocessc                 C   s   |    d S r9   )rH   r<   r2   r2   r3   _clear_preprocess  r_  z%AbstractTableWriter._clear_preprocessc                 C   s   |    |   d S r9   )r3  +_AbstractTableWriter__clear_preprocess_datar<   r2   r2   r3   __clear_preprocess  s   z&AbstractTableWriter.__clear_preprocess)r.   r*   )r.   N)F)T)r  )FT)r  r   r.   Nr9   )a__name__
__module____qualname____doc__FORMAT_NAMEpropertyr   r>   setterr   rE   rM   r   rP   abcabstractmethodrU   r   r   r   r   r   r3  r{  rb   boolr`   ro   r   r   rV   r   r$   rc   r   r   rj   r   rk   rm   rn   dictr   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?  rE  rB  rM  rL  rT  r   r   rX  rR  r(  rG   r   r,  r-  r.  r2  rc  r\  r    r   rf  rA  rh  rt  rx  ry  rz  rH   r2   r2   r2   r3   r6   D   sV   J
I

( 


	%
&#-
2
"

(	C



!







	





r6   )	metaclass)Ir  r  r   rj  r   collections.abcr   typingr   r   r   r   r   r0  datapropertyr   r	   r
   r   r   r   r   dataproperty.typingr   r   r   r   r   r   r   rq   r   errorr   r   r   r   r   r   r   r   r   r   r    r!   r"   typehintr#   r$   _commonr&   
_interfacer'   _msgfyr(   r  tablibrJ   r*   ry   COMMATHOUSAND_SEPARATORSPACE
UNDERSCOREr+   r  r   __annotations__r4   r5   r   ABCMetar6   r2   r2   r2   r3   <module>   s>    $	(
