From c04329f384fe03892a0e9a84ac6d42b54bce4d8f Mon Sep 17 00:00:00 2001 From: Marco Edward Gorelli Date: Sun, 30 Jun 2024 17:04:19 +0100 Subject: [PATCH] add typeguard for is_pandas_dataframe (#362) --- .pre-commit-config.yaml | 1 + narwhals/dependencies.py | 11 ++++++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 70d4bd39b..9d87472b1 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -33,3 +33,4 @@ repos: entry: (?>> )import (pandas|polars|modin|cudf) language: pygrep files: ^narwhals/ + exclude: ^narwhals/dependencies\.py diff --git a/narwhals/dependencies.py b/narwhals/dependencies.py index 64c43d8e9..555407e59 100644 --- a/narwhals/dependencies.py +++ b/narwhals/dependencies.py @@ -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).""" @@ -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