5.1.1.7. Source code writer classes

5.1.1.7.1. JavaScript writer

class pytablewriter.JavaScriptTableWriter(**kwargs)[source]

Bases: SourceCodeTableWriter

A table writer for class JavaScript format.

Example

JavaScript Code

variable_declaration: str = "const"

JavaScript variable declarations type. The value must be either "var", "let" or "const".

write_table()

Write a table to the stream with JavaScript format. The tabular data are written as a nested list variable definition.

Raises

pytablewriter.EmptyTableNameError – If the table_name is empty.

Example

JavaScript Code

Note

Specific values in the tabular data are converted when writing:

  • None: written as null

  • inf: written as Infinity

  • nan: written as NaN

  • datetime.datetime instances determined by is_datetime_instance_formatting attribute:
add_col_separator_style_filter(style_filter: ColSeparatorStyleFilterFunc) None

Add a style filter function for columns to the writer.

Parameters

style_filter

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

class ColSeparatorStyleFilterFunc(Protocol):
    def __call__(
        self, left_cell: Optional[Cell], right_cell: Optional[Cell], **kwargs: Dict[str, 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, default_style will be applied.

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

  • writer: the writer instance that the caller of a style_filter function

add_style_filter(style_filter: StyleFilterFunc) None

Add a style filter function to the writer.

Parameters

style_filter

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

class StyleFilterFunc(Protocol):
    def __call__(self, cell: Cell, **kwargs: Dict[str, 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, default_style will be applied.

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

  • writer: the writer instance that the caller of a style_filter function

clear_theme() None

Remove all of the style filters.

close() None

Close the current stream.

property column_styles: List[Optional[Style]]

Output Style for each column.

Return type

list of Style

dec_indent_level() None

Decrement the indentation level.

property default_style: Style

Default Style of table cells.

dump(output: Union[str, IO], close_after_write: bool = True, **kwargs) None

Write data to the output with tabular format.

During the executing this method, enable_ansi_escape attribute will be temporarily set to False.

Parameters
  • output – The value must either an output stream or a path to an output file.

  • close_after_write – Close the output after write. Defaults to True.

dumps(**kwargs) str

Get rendered tabular text from the table data.

Only available for text format table writers.

Parameters

**kwargs – Optional arguments that the writer takes.

Returns

Rendered tabular text.

Return type

str

property format_name: str

Format name for the writer.

Returns

str

from_csv(csv_source: str, delimiter: str = ',') None

Set tabular attributes to the writer from a character-separated values (CSV) data source. Following attributes are set to the writer by the method:

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

Parameters

csv_source (str) – Input CSV data source either can be designated CSV text or CSV file path.

Examples

Using CSV as tabular data source

Dependency Packages
from_dataframe(dataframe, add_index_column: bool = False, overwrite_type_hints: bool = True) None

Set tabular attributes to the writer from pandas.DataFrame. Following attributes are set by the method:

Parameters
  • dataframe (pandas.DataFrame or str) – Input pandas.DataFrame object or 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

Using pandas DataFrame as tabular data source

from_series(series, add_index_column: bool = True) None

Set tabular attributes to the writer from pandas.Series. Following attributes are set by the method:

Parameters
  • 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.

from_tabledata(value: TableData, is_overwrite_table_name: bool = True) None

Set tabular attributes to the writer from TableData. Following attributes are configured:

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

Parameters

value (tabledata.TableData) – Input table data.

from_tablib(tablib_dataset) None

Set tabular attributes to the writer from tablib.Dataset.

from_writer(writer: AbstractTableWriter, is_overwrite_table_name: bool = True) None

Set tabular attributes to the writer from an another table writer class incetance.

property headers: Sequence[str]

Headers of a table to be outputted.

inc_indent_level() None

Increment the indentation level.

set_indent_level(indent_level: int) None

Set the indentation level.

Parameters

indent_level (int) – New indentation level.

set_style(column: Union[str, int], style: Style) None

Set Style for a specific column.

Parameters
  • 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 – If the column specifier is invalid.

set_theme(theme: str, **kwargs) None

Set style filters for a theme.

Parameters

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 installed.

property support_split_write: bool

Represents the writer class supported iterative table writing (write_table_iter method).

Returns

True if the writer supported iterative table writing.

Return type

bool

property table_format

Get the format of the writer.

Return type

TableFormat

property table_name: str

Name of a table.

property tabledata: TableData

Get tabular data of the writer.

Return type

tabledata.TableData

property type_hints: List[Optional[Type[AbstractType]]]

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)

  • pytablewriter.typehint.Bool or "bool"

  • pytablewriter.typehint.DateTime or "datetime"

  • pytablewriter.typehint.Dictionary or "dict"

  • pytablewriter.typehint.Infinity or "inf"

  • pytablewriter.typehint.Integer or "int"

  • pytablewriter.typehint.IpAddress or "ipaddr"

  • pytablewriter.typehint.List or "list"

  • pytablewriter.typehint.Nan or "nan"

  • pytablewriter.typehint.NoneType or "none"

  • pytablewriter.typehint.NullString or "nullstr"

  • pytablewriter.typehint.RealNumber or "realnumber" or "float"

  • 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 detect column data type from the column data.

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

Defaults to None.

Examples
property value_matrix: Sequence

Data of a table to be outputted.

property variable_name: str

Return a valid variable name that converted from the table_name.

Returns

A variable name.

Return type

str

write_null_line() None

Write a null line to the stream.

write_table(**kwargs) None

Write a table to the stream.

Parameters

indent (Optional[int]) – Indent level of an output. Interpretation of indent level value differ format to format. Some writer classes may ignore this value.

Note

  • None values are written as an empty string.

write_table_iter(**kwargs) None

Write a table with iteration. “Iteration” means that divide the table writing into multiple processes. This method is useful, especially for large data. The following are premises to execute this method:

  • set iterator to the value_matrix

  • set the number of iterations to the iteration_length attribute

Call back function (Optional): Callback function is called when for each of the iteration of writing a table is completed. To set call back function, set a callback function to the write_callback attribute.

Raises

pytablewriter.NotSupportedError – If the class does not support this method.

Note

Following classes do not support this method: HtmlTableWriter, RstGridTableWriter, RstSimpleTableWriter. support_split_write attribute return True if the class is supporting this method.

5.1.1.7.2. NumPy table writer

class pytablewriter.NumpyTableWriter(**kwargs)[source]

Bases: PythonCodeTableWriter

A table writer class for NumPy source code format.

Example

NumPy array

write_table()

Write a table to the stream with NumPy format. The tabular data are written as a variable definition of numpy.array.

Raises

pytablewriter.EmptyTableNameError – If the table_name is empty.

Example

NumPy array

Note

Specific values in the tabular data are converted when writing:

  • None: written as None

  • inf: written as numpy.inf

  • nan: written as numpy.nan

  • datetime.datetime instances determined by is_datetime_instance_formatting attribute:
add_col_separator_style_filter(style_filter: ColSeparatorStyleFilterFunc) None

Add a style filter function for columns to the writer.

Parameters

style_filter

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

class ColSeparatorStyleFilterFunc(Protocol):
    def __call__(
        self, left_cell: Optional[Cell], right_cell: Optional[Cell], **kwargs: Dict[str, 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, default_style will be applied.

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

  • writer: the writer instance that the caller of a style_filter function

add_style_filter(style_filter: StyleFilterFunc) None

Add a style filter function to the writer.

Parameters

style_filter

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

class StyleFilterFunc(Protocol):
    def __call__(self, cell: Cell, **kwargs: Dict[str, 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, default_style will be applied.

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

  • writer: the writer instance that the caller of a style_filter function

clear_theme() None

Remove all of the style filters.

close() None

Close the current stream.

property column_styles: List[Optional[Style]]

Output Style for each column.

Return type

list of Style

dec_indent_level() None

Decrement the indentation level.

property default_style: Style

Default Style of table cells.

dump(output: Union[str, IO], close_after_write: bool = True, **kwargs) None

Write data to the output with tabular format.

During the executing this method, enable_ansi_escape attribute will be temporarily set to False.

Parameters
  • output – The value must either an output stream or a path to an output file.

  • close_after_write – Close the output after write. Defaults to True.

dumps(**kwargs) str

Get rendered tabular text from the table data.

Only available for text format table writers.

Parameters

**kwargs – Optional arguments that the writer takes.

Returns

Rendered tabular text.

Return type

str

property format_name: str

Format name for the writer.

Returns

str

from_csv(csv_source: str, delimiter: str = ',') None

Set tabular attributes to the writer from a character-separated values (CSV) data source. Following attributes are set to the writer by the method:

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

Parameters

csv_source (str) – Input CSV data source either can be designated CSV text or CSV file path.

Examples

Using CSV as tabular data source

Dependency Packages
from_dataframe(dataframe, add_index_column: bool = False, overwrite_type_hints: bool = True) None

Set tabular attributes to the writer from pandas.DataFrame. Following attributes are set by the method:

Parameters
  • dataframe (pandas.DataFrame or str) – Input pandas.DataFrame object or 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

Using pandas DataFrame as tabular data source

from_series(series, add_index_column: bool = True) None

Set tabular attributes to the writer from pandas.Series. Following attributes are set by the method:

Parameters
  • 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.

from_tabledata(value: TableData, is_overwrite_table_name: bool = True) None

Set tabular attributes to the writer from TableData. Following attributes are configured:

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

Parameters

value (tabledata.TableData) – Input table data.

from_tablib(tablib_dataset) None

Set tabular attributes to the writer from tablib.Dataset.

from_writer(writer: AbstractTableWriter, is_overwrite_table_name: bool = True) None

Set tabular attributes to the writer from an another table writer class incetance.

property headers: Sequence[str]

Headers of a table to be outputted.

inc_indent_level() None

Increment the indentation level.

set_indent_level(indent_level: int) None

Set the indentation level.

Parameters

indent_level (int) – New indentation level.

set_style(column: Union[str, int], style: Style) None

Set Style for a specific column.

Parameters
  • 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 – If the column specifier is invalid.

set_theme(theme: str, **kwargs) None

Set style filters for a theme.

Parameters

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 installed.

property support_split_write: bool

Represents the writer class supported iterative table writing (write_table_iter method).

Returns

True if the writer supported iterative table writing.

Return type

bool

property table_format

Get the format of the writer.

Return type

TableFormat

property table_name: str

Name of a table.

property tabledata: TableData

Get tabular data of the writer.

Return type

tabledata.TableData

property type_hints: List[Optional[Type[AbstractType]]]

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)

  • pytablewriter.typehint.Bool or "bool"

  • pytablewriter.typehint.DateTime or "datetime"

  • pytablewriter.typehint.Dictionary or "dict"

  • pytablewriter.typehint.Infinity or "inf"

  • pytablewriter.typehint.Integer or "int"

  • pytablewriter.typehint.IpAddress or "ipaddr"

  • pytablewriter.typehint.List or "list"

  • pytablewriter.typehint.Nan or "nan"

  • pytablewriter.typehint.NoneType or "none"

  • pytablewriter.typehint.NullString or "nullstr"

  • pytablewriter.typehint.RealNumber or "realnumber" or "float"

  • 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 detect column data type from the column data.

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

Defaults to None.

Examples
property value_matrix: Sequence

Data of a table to be outputted.

property variable_name: str

Return a valid variable name that converted from the table_name.

Returns

A variable name.

Return type

str

write_null_line() None

Write a null line to the stream.

write_table(**kwargs) None

Write a table to the stream.

Parameters

indent (Optional[int]) – Indent level of an output. Interpretation of indent level value differ format to format. Some writer classes may ignore this value.

Note

  • None values are written as an empty string.

write_table_iter(**kwargs) None

Write a table with iteration. “Iteration” means that divide the table writing into multiple processes. This method is useful, especially for large data. The following are premises to execute this method:

  • set iterator to the value_matrix

  • set the number of iterations to the iteration_length attribute

Call back function (Optional): Callback function is called when for each of the iteration of writing a table is completed. To set call back function, set a callback function to the write_callback attribute.

Raises

pytablewriter.NotSupportedError – If the class does not support this method.

Note

Following classes do not support this method: HtmlTableWriter, RstGridTableWriter, RstSimpleTableWriter. support_split_write attribute return True if the class is supporting this method.

5.1.1.7.3. Pandas DataFrame writer

class pytablewriter.PandasDataFrameWriter(**kwargs)[source]

Bases: NumpyTableWriter

A writer class for Pandas DataFrame format.

import_pandas_as: str = "pd"

Specify pandas module import name of an output source code.

import_numpy_as: str = "np"

Specify numpy module import name of an output source code.

write_table()

Write a table to the stream with Pandas DataFrame format. The tabular data are written as a pandas.DataFrame class instance definition.

Raises

pytablewriter.EmptyTableNameError – If the table_name is empty.

Example

Pandas DataFrame

Note

Specific values in the tabular data are converted when writing:

  • None: written as None

  • inf: written as numpy.inf

  • nan: written as numpy.nan

  • datetime.datetime instances determined by is_datetime_instance_formatting attribute:
add_col_separator_style_filter(style_filter: ColSeparatorStyleFilterFunc) None

Add a style filter function for columns to the writer.

Parameters

style_filter

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

class ColSeparatorStyleFilterFunc(Protocol):
    def __call__(
        self, left_cell: Optional[Cell], right_cell: Optional[Cell], **kwargs: Dict[str, 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, default_style will be applied.

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

  • writer: the writer instance that the caller of a style_filter function

add_style_filter(style_filter: StyleFilterFunc) None

Add a style filter function to the writer.

Parameters

style_filter

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

class StyleFilterFunc(Protocol):
    def __call__(self, cell: Cell, **kwargs: Dict[str, 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, default_style will be applied.

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

  • writer: the writer instance that the caller of a style_filter function

clear_theme() None

Remove all of the style filters.

close() None

Close the current stream.

property column_styles: List[Optional[Style]]

Output Style for each column.

Return type

list of Style

dec_indent_level() None

Decrement the indentation level.

property default_style: Style

Default Style of table cells.

dump(output: Union[str, IO], close_after_write: bool = True, **kwargs) None

Write data to the output with tabular format.

During the executing this method, enable_ansi_escape attribute will be temporarily set to False.

Parameters
  • output – The value must either an output stream or a path to an output file.

  • close_after_write – Close the output after write. Defaults to True.

dumps(**kwargs) str

Get rendered tabular text from the table data.

Only available for text format table writers.

Parameters

**kwargs – Optional arguments that the writer takes.

Returns

Rendered tabular text.

Return type

str

property format_name: str

Format name for the writer.

Returns

str

from_csv(csv_source: str, delimiter: str = ',') None

Set tabular attributes to the writer from a character-separated values (CSV) data source. Following attributes are set to the writer by the method:

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

Parameters

csv_source (str) – Input CSV data source either can be designated CSV text or CSV file path.

Examples

Using CSV as tabular data source

Dependency Packages
from_dataframe(dataframe, add_index_column: bool = False, overwrite_type_hints: bool = True) None

Set tabular attributes to the writer from pandas.DataFrame. Following attributes are set by the method:

Parameters
  • dataframe (pandas.DataFrame or str) – Input pandas.DataFrame object or 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

Using pandas DataFrame as tabular data source

from_series(series, add_index_column: bool = True) None

Set tabular attributes to the writer from pandas.Series. Following attributes are set by the method:

Parameters
  • 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.

from_tabledata(value: TableData, is_overwrite_table_name: bool = True) None

Set tabular attributes to the writer from TableData. Following attributes are configured:

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

Parameters

value (tabledata.TableData) – Input table data.

from_tablib(tablib_dataset) None

Set tabular attributes to the writer from tablib.Dataset.

from_writer(writer: AbstractTableWriter, is_overwrite_table_name: bool = True) None

Set tabular attributes to the writer from an another table writer class incetance.

property headers: Sequence[str]

Headers of a table to be outputted.

inc_indent_level() None

Increment the indentation level.

set_indent_level(indent_level: int) None

Set the indentation level.

Parameters

indent_level (int) – New indentation level.

set_style(column: Union[str, int], style: Style) None

Set Style for a specific column.

Parameters
  • 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 – If the column specifier is invalid.

set_theme(theme: str, **kwargs) None

Set style filters for a theme.

Parameters

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 installed.

property support_split_write: bool

Represents the writer class supported iterative table writing (write_table_iter method).

Returns

True if the writer supported iterative table writing.

Return type

bool

property table_format

Get the format of the writer.

Return type

TableFormat

property table_name: str

Name of a table.

property tabledata: TableData

Get tabular data of the writer.

Return type

tabledata.TableData

property type_hints: List[Optional[Type[AbstractType]]]

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)

  • pytablewriter.typehint.Bool or "bool"

  • pytablewriter.typehint.DateTime or "datetime"

  • pytablewriter.typehint.Dictionary or "dict"

  • pytablewriter.typehint.Infinity or "inf"

  • pytablewriter.typehint.Integer or "int"

  • pytablewriter.typehint.IpAddress or "ipaddr"

  • pytablewriter.typehint.List or "list"

  • pytablewriter.typehint.Nan or "nan"

  • pytablewriter.typehint.NoneType or "none"

  • pytablewriter.typehint.NullString or "nullstr"

  • pytablewriter.typehint.RealNumber or "realnumber" or "float"

  • 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 detect column data type from the column data.

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

Defaults to None.

Examples
property value_matrix: Sequence

Data of a table to be outputted.

property variable_name: str

Return a valid variable name that converted from the table_name.

Returns

A variable name.

Return type

str

write_null_line() None

Write a null line to the stream.

write_table(**kwargs) None

Write a table to the stream.

Parameters

indent (Optional[int]) – Indent level of an output. Interpretation of indent level value differ format to format. Some writer classes may ignore this value.

Note

  • None values are written as an empty string.

write_table_iter(**kwargs) None

Write a table with iteration. “Iteration” means that divide the table writing into multiple processes. This method is useful, especially for large data. The following are premises to execute this method:

  • set iterator to the value_matrix

  • set the number of iterations to the iteration_length attribute

Call back function (Optional): Callback function is called when for each of the iteration of writing a table is completed. To set call back function, set a callback function to the write_callback attribute.

Raises

pytablewriter.NotSupportedError – If the class does not support this method.

Note

Following classes do not support this method: HtmlTableWriter, RstGridTableWriter, RstSimpleTableWriter. support_split_write attribute return True if the class is supporting this method.

5.1.1.7.4. Python table writer

class pytablewriter.PythonCodeTableWriter(**kwargs)[source]

Bases: SourceCodeTableWriter

A table writer class for Python source code format.

Example

Python Code

write_table()

Write a table to the stream with Python format. The tabular data are written as a nested list variable definition for Python format.

Raises

pytablewriter.EmptyTableNameError – If the table_name is empty.

Example

Python Code

Note

Specific values in the tabular data are converted when writing:

  • None: written as None

  • inf: written as float("inf")

  • nan: written as float("nan")

  • datetime.datetime instances determined by is_datetime_instance_formatting attribute:
add_col_separator_style_filter(style_filter: ColSeparatorStyleFilterFunc) None

Add a style filter function for columns to the writer.

Parameters

style_filter

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

class ColSeparatorStyleFilterFunc(Protocol):
    def __call__(
        self, left_cell: Optional[Cell], right_cell: Optional[Cell], **kwargs: Dict[str, 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, default_style will be applied.

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

  • writer: the writer instance that the caller of a style_filter function

add_style_filter(style_filter: StyleFilterFunc) None

Add a style filter function to the writer.

Parameters

style_filter

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

class StyleFilterFunc(Protocol):
    def __call__(self, cell: Cell, **kwargs: Dict[str, 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, default_style will be applied.

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

  • writer: the writer instance that the caller of a style_filter function

clear_theme() None

Remove all of the style filters.

close() None

Close the current stream.

property column_styles: List[Optional[Style]]

Output Style for each column.

Return type

list of Style

dec_indent_level() None

Decrement the indentation level.

property default_style: Style

Default Style of table cells.

dump(output: Union[str, IO], close_after_write: bool = True, **kwargs) None

Write data to the output with tabular format.

During the executing this method, enable_ansi_escape attribute will be temporarily set to False.

Parameters
  • output – The value must either an output stream or a path to an output file.

  • close_after_write – Close the output after write. Defaults to True.

dumps(**kwargs) str

Get rendered tabular text from the table data.

Only available for text format table writers.

Parameters

**kwargs – Optional arguments that the writer takes.

Returns

Rendered tabular text.

Return type

str

property format_name: str

Format name for the writer.

Returns

str

from_csv(csv_source: str, delimiter: str = ',') None

Set tabular attributes to the writer from a character-separated values (CSV) data source. Following attributes are set to the writer by the method:

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

Parameters

csv_source (str) – Input CSV data source either can be designated CSV text or CSV file path.

Examples

Using CSV as tabular data source

Dependency Packages
from_dataframe(dataframe, add_index_column: bool = False, overwrite_type_hints: bool = True) None

Set tabular attributes to the writer from pandas.DataFrame. Following attributes are set by the method:

Parameters
  • dataframe (pandas.DataFrame or str) – Input pandas.DataFrame object or 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

Using pandas DataFrame as tabular data source

from_series(series, add_index_column: bool = True) None

Set tabular attributes to the writer from pandas.Series. Following attributes are set by the method:

Parameters
  • 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.

from_tabledata(value: TableData, is_overwrite_table_name: bool = True) None

Set tabular attributes to the writer from TableData. Following attributes are configured:

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

Parameters

value (tabledata.TableData) – Input table data.

from_tablib(tablib_dataset) None

Set tabular attributes to the writer from tablib.Dataset.

from_writer(writer: AbstractTableWriter, is_overwrite_table_name: bool = True) None

Set tabular attributes to the writer from an another table writer class incetance.

property headers: Sequence[str]

Headers of a table to be outputted.

inc_indent_level() None

Increment the indentation level.

set_indent_level(indent_level: int) None

Set the indentation level.

Parameters

indent_level (int) – New indentation level.

set_style(column: Union[str, int], style: Style) None

Set Style for a specific column.

Parameters
  • 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 – If the column specifier is invalid.

set_theme(theme: str, **kwargs) None

Set style filters for a theme.

Parameters

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 installed.

property support_split_write: bool

Represents the writer class supported iterative table writing (write_table_iter method).

Returns

True if the writer supported iterative table writing.

Return type

bool

property table_format

Get the format of the writer.

Return type

TableFormat

property table_name: str

Name of a table.

property tabledata: TableData

Get tabular data of the writer.

Return type

tabledata.TableData

property type_hints: List[Optional[Type[AbstractType]]]

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)

  • pytablewriter.typehint.Bool or "bool"

  • pytablewriter.typehint.DateTime or "datetime"

  • pytablewriter.typehint.Dictionary or "dict"

  • pytablewriter.typehint.Infinity or "inf"

  • pytablewriter.typehint.Integer or "int"

  • pytablewriter.typehint.IpAddress or "ipaddr"

  • pytablewriter.typehint.List or "list"

  • pytablewriter.typehint.Nan or "nan"

  • pytablewriter.typehint.NoneType or "none"

  • pytablewriter.typehint.NullString or "nullstr"

  • pytablewriter.typehint.RealNumber or "realnumber" or "float"

  • 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 detect column data type from the column data.

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

Defaults to None.

Examples
property value_matrix: Sequence

Data of a table to be outputted.

property variable_name: str

Return a valid variable name that converted from the table_name.

Returns

A variable name.

Return type

str

write_null_line() None

Write a null line to the stream.

write_table(**kwargs) None

Write a table to the stream.

Parameters

indent (Optional[int]) – Indent level of an output. Interpretation of indent level value differ format to format. Some writer classes may ignore this value.

Note

  • None values are written as an empty string.

write_table_iter(**kwargs) None

Write a table with iteration. “Iteration” means that divide the table writing into multiple processes. This method is useful, especially for large data. The following are premises to execute this method:

  • set iterator to the value_matrix

  • set the number of iterations to the iteration_length attribute

Call back function (Optional): Callback function is called when for each of the iteration of writing a table is completed. To set call back function, set a callback function to the write_callback attribute.

Raises

pytablewriter.NotSupportedError – If the class does not support this method.

Note

Following classes do not support this method: HtmlTableWriter, RstGridTableWriter, RstSimpleTableWriter. support_split_write attribute return True if the class is supporting this method.