5.1.4.1. Abstract classes

class pytablewriter.writer._interface.TableWriterInterface[source]

Interface class for writing a table.

abstract property format_name: str

Format name for the writer.

Returns:

str

abstract property support_split_write: bool

Indicates whether the writer class supports iterative table writing (write_table_iter) method.

Returns:

True if the writer supported iterative table writing.

Return type:

bool

abstract write_table(**kwargs: Any) None[source]

Write a table to the stream.

write_table_iter(**kwargs: Any) None[source]

Write a table with iteration. “Iteration” means that divide the table writing into multiple writes. This method is helpful, especially for extensive data. The following are the 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): A callback function is called when each iteration of writing a table is completed. You can set a callback function via the write_callback attribute.

Raises:

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

Note

The following classes do not support this method:

support_split_write attribute return True if the class is supporting this method.

class pytablewriter.AbstractTableWriter(**kwargs: Any)[source]

Bases: TableWriterInterface

An abstract base class of table writer classes.

Parameters:
  • max_precision (int) – Maximum decimal places for real number values.

  • dequote (bool) – If True, dequote values in value_matrix.

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:

Configure Output Stream

is_write_header: bool

Write headers of a table if the value is True.

is_padding: bool

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

iteration_length: int

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

style_filter_kwargs: Dict[str, Any]

Extra keyword arguments for style filter functions. These arguments will pass to filter functions added by add_style_filter() or add_col_separator_style_filter()

colorize_terminal: bool = True

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

enable_ansi_escape: bool = True

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

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:

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

add_style_filter(style_filter: StyleFilterFunc) None[source]

Add a style filter function to the writer.

Parameters:

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:

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, default_style will be used.

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[source]

Remove all of the style filters.

close() None[source]

Close the current stream.

property column_styles: List[Style | None]

Style for each column.

Type:

List[Optional[Style]]

property default_style: Style

Default Style of table cells.

Type:

Style

disable_style_filter(clear_filters: bool = False) None[source]

Disable style filters.

Parameters:

clear_filters (bool) – If True, clear all of the style filters. Defaults to False.

enable_style_filter() None[source]

Enable style filters.

from_csv(csv_source: str, delimiter: str = ',') None[source]

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:

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 can be designated CSV text or a CSV file path.

  • delimiter (str) – Delimiter character of the CSV data source. Defaults to ,.

Examples

Using CSV as a tabular data source

Dependency Packages:
from_dataframe(dataframe: pandas.DataFrame, add_index_column: bool = False, overwrite_type_hints: bool = True) None[source]

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

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

Using pandas DataFrame as a tabular data source

from_series(series: pandas.Series, add_index_column: bool = True) None[source]

Set tabular attributes to the writer from pandas.Series. The 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[source]

Set tabular attributes to the writer from TableData. The 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: tablib.Dataset) None[source]

Set tabular attributes to the writer from tablib.Dataset.

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

Copy attributes from another table writer class instance.

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

property headers: Sequence[str]

Headers of a table to be outputted.

Type:

Sequence[str]

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

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 – Raised when the column specifier is invalid.

set_theme(theme: str, **kwargs: Any) None[source]

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

property table_format: TableFormat

Get the format of the writer.

Type:

TableFormat

property table_name: str

Name of a table.

Type:

str

property tabledata: TableData

Get tabular data of the writer.

Type:

tabledata.TableData

property type_hints: List[Type[AbstractType] | None]

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

property value_matrix: Sequence

Data of a table to be outputted.

write_table(**kwargs: Any) None[source]

Write a table to the stream.