Skip to content

Commit 280da38

Browse files
committed
Refactor to_latex using polymorphism
Previously there was a complicated logic in multiple methods for either longtable or regular table. This commit implements - ``LatexTableFormatter``, - ``LatexTabularFormatter``, - ``LatexLongTableFormatter``, derived from ``LatexFormatter``, based on ``LatexFormatterAbstract``. Each of the derived classes implements its own methods for writing - beginning of the table; - caption and labels; - separators; - end of the table. LatexFormatter changes ---------------------- - Make the process of creating tables more readable. - Drop escape and bold_rows attr
1 parent a23af4e commit 280da38

File tree

2 files changed

+307
-177
lines changed

2 files changed

+307
-177
lines changed

pandas/io/formats/format.py

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -936,19 +936,35 @@ def to_latex(
936936
"""
937937
Render a DataFrame to a LaTeX tabular/longtable environment output.
938938
"""
939-
from pandas.io.formats.latex import LatexFormatter
940-
941-
return LatexFormatter(
942-
self,
943-
column_format=column_format,
939+
latex_formatter = self._create_latex_formatter(
944940
longtable=longtable,
941+
column_format=column_format,
945942
multicolumn=multicolumn,
946943
multicolumn_format=multicolumn_format,
947944
multirow=multirow,
948945
caption=caption,
949946
label=label,
950947
position=position,
951-
).get_result(buf=buf, encoding=encoding)
948+
)
949+
return latex_formatter.get_result(buf=buf, encoding=encoding)
950+
951+
def _create_latex_formatter(self, **kwargs):
952+
"""Create concrete instance of LatexFormatter."""
953+
from pandas.io.formats.latex import (
954+
LatexLongTableFormatter,
955+
LatexTableFormatter,
956+
LatexTabularFormatter,
957+
)
958+
959+
is_longtable = kwargs.pop("longtable")
960+
is_table = any(
961+
[kwargs.get("caption"), kwargs.get("label"), kwargs.get("position")]
962+
)
963+
if is_longtable:
964+
return LatexLongTableFormatter(self, **kwargs)
965+
if is_table:
966+
return LatexTableFormatter(self, **kwargs)
967+
return LatexTabularFormatter(self, **kwargs)
952968

953969
def _format_col(self, i: int) -> List[str]:
954970
frame = self.tr_frame

0 commit comments

Comments
 (0)