Skip to content

Commit

Permalink
add typeguard for is_pandas_dataframe (#362)
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoGorelli authored Jun 30, 2024
1 parent 44b12db commit c04329f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
1 change: 1 addition & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,4 @@ repos:
entry: (?<!>>> )import (pandas|polars|modin|cudf)
language: pygrep
files: ^narwhals/
exclude: ^narwhals/dependencies\.py
11 changes: 10 additions & 1 deletion narwhals/dependencies.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
# pandas / Polars / etc. : if a user passes a dataframe from one of these
# libraries, it means they must already have imported the given module.
# So, we can just check sys.modules.
from __future__ import annotations

import sys
from typing import TYPE_CHECKING
from typing import Any

if TYPE_CHECKING:
if sys.version_info >= (3, 10):
from typing import TypeGuard
else:
from typing_extensions import TypeGuard
import pandas


def get_polars() -> Any:
"""Get Polars module (if already imported - else return None)."""
Expand Down Expand Up @@ -47,7 +56,7 @@ def get_numpy() -> Any:
return sys.modules.get("numpy", None)


def is_pandas_dataframe(df: Any) -> bool:
def is_pandas_dataframe(df: Any) -> TypeGuard[pandas.DataFrame]:
"""Check whether `df` is a pandas DataFrame without importing pandas."""
if (pd := get_pandas()) is not None and isinstance(df, pd.DataFrame):
return True
Expand Down

0 comments on commit c04329f

Please sign in to comment.