fixed missing optional dependency of pandas/Styler

This commit is contained in:
Nicolas 2025-05-26 10:13:34 +02:00
parent 76944d1829
commit 250885d44f
2 changed files with 14 additions and 4 deletions

View File

@ -33,6 +33,7 @@ else:
Table = DataFrame | Styler Table = DataFrame | Styler
except ImportError: except ImportError:
Table = DataFrame Table = DataFrame
Styler = None
try: try:
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
@ -475,8 +476,8 @@ class DocumentWriter():
centered: Whether to center the table in LaTeX output centered: Whether to center the table in LaTeX output
""" """
assert Table and isinstance(table, Table), 'Table has to be a pandas DataFrame oder DataFrame Styler' assert Table and isinstance(table, Table), 'Table has to be a pandas DataFrame oder DataFrame Styler'
styler = table if isinstance(table, Styler) else getattr(table, 'style', None) styler = table if Styler and isinstance(table, Styler) else getattr(table, 'style', None) # type: ignore[truthy-function]
assert isinstance(styler, Styler), 'Jinja2 package is required for rendering tables' assert Styler and isinstance(styler, Styler), 'Jinja2 package is required for rendering pandas tables' # type: ignore[truthy-function]
def render_to_html() -> str: def render_to_html() -> str:
caption_prefix, reference = self._add_item(ref_id, ref_type, prefix_pattern) caption_prefix, reference = self._add_item(ref_id, ref_type, prefix_pattern)

View File

@ -1,6 +1,5 @@
from html.parser import HTMLParser from html.parser import HTMLParser
from typing import Generator, Any, Literal, get_args from typing import Generator, Any, Literal, get_args, TYPE_CHECKING
from pandas.io.formats.style import Styler
import re import re
import os import os
import shutil import shutil
@ -8,6 +7,13 @@ import subprocess
import tempfile import tempfile
from .latex_escaping import unicode_to_latex_dict, latex_escape_dict from .latex_escaping import unicode_to_latex_dict, latex_escape_dict
if TYPE_CHECKING:
from pandas.io.formats.style import Styler
else:
try:
from pandas.io.formats.style import Styler
except ImportError:
Styler = None
LatexEngine = Literal['pdflatex', 'lualatex', 'xelatex', 'tectonic'] LatexEngine = Literal['pdflatex', 'lualatex', 'xelatex', 'tectonic']
@ -116,6 +122,9 @@ def render_pandas_styler_table(df_style: Styler, caption: str = '', label: str =
Returns: Returns:
The LaTeX code. The LaTeX code.
""" """
assert Styler, 'Jinja2 package is required for rendering pandas tables'
assert isinstance(df_style, Styler), 'df_style has to be of type Styler'
def iter_table(table: dict[str, Any]) -> Generator[str, None, None]: def iter_table(table: dict[str, Any]) -> Generator[str, None, None]:
yield '\\begin{table}\n' yield '\\begin{table}\n'
if centering: if centering: