|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from importlib.util import find_spec |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +from great_tables._tbl_data import DataFrameLike, _re_version |
| 8 | +from tests.utils import DataFrameConstructor, DataLike |
| 9 | + |
| 10 | + |
| 11 | +def pandas_constructor(obj: DataLike) -> DataFrameLike: |
| 12 | + import pandas as pd |
| 13 | + |
| 14 | + return pd.DataFrame(obj) # type: ignore[no-any-return] |
| 15 | + |
| 16 | + |
| 17 | +def pandas_nullable_constructor(obj: DataLike) -> DataFrameLike: |
| 18 | + import pandas as pd |
| 19 | + |
| 20 | + return pd.DataFrame(obj).convert_dtypes(dtype_backend="numpy_nullable") # type: ignore[no-any-return] |
| 21 | + |
| 22 | + |
| 23 | +def pandas_pyarrow_constructor(obj: DataLike) -> DataFrameLike: |
| 24 | + import pandas as pd |
| 25 | + |
| 26 | + return pd.DataFrame(obj).convert_dtypes(dtype_backend="pyarrow") # type: ignore[no-any-return] |
| 27 | + |
| 28 | + |
| 29 | +def polars_constructor(obj: DataLike) -> DataFrameLike: |
| 30 | + import polars as pl |
| 31 | + |
| 32 | + return pl.DataFrame(obj) |
| 33 | + |
| 34 | + |
| 35 | +def pyarrow_table_constructor(obj: DataLike) -> DataFrameLike: |
| 36 | + import pyarrow as pa |
| 37 | + |
| 38 | + return pa.table(obj) # type: ignore[no-any-return] |
| 39 | + |
| 40 | + |
| 41 | +frame_constructors: list[DataFrameConstructor] = [] |
| 42 | + |
| 43 | +is_pandas_installed = find_spec("pandas") is not None |
| 44 | +is_polars_installed = find_spec("polars") is not None |
| 45 | +is_pyarrow_installed = find_spec("pyarrow") is not None |
| 46 | + |
| 47 | +if is_pandas_installed: |
| 48 | + import pandas as pd |
| 49 | + |
| 50 | + frame_constructors.append(pandas_constructor) |
| 51 | + |
| 52 | + pandas_ge_v2 = _re_version(pd.__version__) >= (2, 0, 0) |
| 53 | + |
| 54 | + if pandas_ge_v2: |
| 55 | + frame_constructors.append(pandas_nullable_constructor) |
| 56 | + |
| 57 | + if pandas_ge_v2 and is_pyarrow_installed: |
| 58 | + # pandas 2.0+ supports pyarrow dtype backend |
| 59 | + # https://pandas.pydata.org/docs/whatsnew/v2.0.0.html#new-dtype-backends |
| 60 | + frame_constructors.append(pandas_pyarrow_constructor) |
| 61 | + |
| 62 | +if is_polars_installed: |
| 63 | + frame_constructors.append(polars_constructor) |
| 64 | + |
| 65 | +if is_pyarrow_installed: |
| 66 | + frame_constructors.append(pyarrow_table_constructor) |
| 67 | + |
| 68 | + |
| 69 | +@pytest.fixture(params=frame_constructors) |
| 70 | +def frame_constructor(request: pytest.FixtureRequest) -> DataFrameConstructor: |
| 71 | + return request.param # type: ignore[no-any-return] |
0 commit comments