content stringlengths 1 103k ⌀ | path stringlengths 8 216 | filename stringlengths 2 179 | language stringclasses 15
values | size_bytes int64 2 189k | quality_score float64 0.5 0.95 | complexity float64 0 1 | documentation_ratio float64 0 1 | repository stringclasses 5
values | stars int64 0 1k | created_date stringdate 2023-07-10 19:21:08 2025-07-09 19:11:45 | license stringclasses 4
values | is_test bool 2
classes | file_hash stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
from __future__ import annotations\n\nimport functools\nimport re\nfrom typing import TYPE_CHECKING, Any, Callable, Literal, TypeVar\n\nimport pandas as pd\n\nfrom narwhals._compliant.series import EagerSeriesNamespace\nfrom narwhals._constants import (\n MS_PER_SECOND,\n NS_PER_MICROSECOND,\n NS_PER_MILLISECOND,\n NS_PER_SECOND,\n SECONDS_PER_DAY,\n US_PER_SECOND,\n)\nfrom narwhals._utils import (\n Implementation,\n Version,\n _DeferredIterable,\n check_columns_exist,\n isinstance_or_issubclass,\n)\nfrom narwhals.exceptions import ShapeError\n\nif TYPE_CHECKING:\n from types import ModuleType\n\n from pandas._typing import Dtype as PandasDtype\n from pandas.core.dtypes.dtypes import BaseMaskedDtype\n from typing_extensions import TypeIs\n\n from narwhals._pandas_like.expr import PandasLikeExpr\n from narwhals._pandas_like.series import PandasLikeSeries\n from narwhals._pandas_like.typing import (\n NativeDataFrameT,\n NativeNDFrameT,\n NativeSeriesT,\n )\n from narwhals.dtypes import DType\n from narwhals.typing import DTypeBackend, IntoDType, TimeUnit, _1DArray\n\n ExprT = TypeVar("ExprT", bound=PandasLikeExpr)\n\n\nPANDAS_LIKE_IMPLEMENTATION = {\n Implementation.PANDAS,\n Implementation.CUDF,\n Implementation.MODIN,\n}\nPD_DATETIME_RGX = r"""^\n datetime64\[\n (?P<time_unit>s|ms|us|ns) # Match time unit: s, ms, us, or ns\n (?:, # Begin non-capturing group for optional timezone\n \s* # Optional whitespace after comma\n (?P<time_zone> # Start named group for timezone\n [a-zA-Z\/]+ # Match timezone name, e.g., UTC, America/New_York\n (?:[+-]\d{2}:\d{2})? # Optional offset in format +HH:MM or -HH:MM\n | # OR\n pytz\.FixedOffset\(\d+\) # Match pytz.FixedOffset with integer offset in parentheses\n ) # End time_zone group\n )? # End optional timezone group\n \] # Closing bracket for datetime64\n$"""\nPATTERN_PD_DATETIME = re.compile(PD_DATETIME_RGX, re.VERBOSE)\nPA_DATETIME_RGX = r"""^\n timestamp\[\n (?P<time_unit>s|ms|us|ns) # Match time unit: s, ms, us, or ns\n (?:, # Begin non-capturing group for optional timezone\n \s?tz= # Match "tz=" prefix\n (?P<time_zone> # Start named group for timezone\n [a-zA-Z\/]* # Match timezone name (e.g., UTC, America/New_York)\n (?: # Begin optional non-capturing group for offset\n [+-]\d{2}:\d{2} # Match offset in format +HH:MM or -HH:MM\n )? # End optional offset group\n ) # End time_zone group\n )? # End optional timezone group\n \] # Closing bracket for timestamp\n \[pyarrow\] # Literal string "[pyarrow]"\n$"""\nPATTERN_PA_DATETIME = re.compile(PA_DATETIME_RGX, re.VERBOSE)\nPD_DURATION_RGX = r"""^\n timedelta64\[\n (?P<time_unit>s|ms|us|ns) # Match time unit: s, ms, us, or ns\n \] # Closing bracket for timedelta64\n$"""\n\nPATTERN_PD_DURATION = re.compile(PD_DURATION_RGX, re.VERBOSE)\nPA_DURATION_RGX = r"""^\n duration\[\n (?P<time_unit>s|ms|us|ns) # Match time unit: s, ms, us, or ns\n \] # Closing bracket for duration\n \[pyarrow\] # Literal string "[pyarrow]"\n$"""\nPATTERN_PA_DURATION = re.compile(PA_DURATION_RGX, re.VERBOSE)\n\nUNIT_DICT = {"d": "D", "m": "min"}\n\n\ndef align_and_extract_native(\n lhs: PandasLikeSeries, rhs: PandasLikeSeries | object\n) -> tuple[pd.Series[Any] | object, pd.Series[Any] | object]:\n """Validate RHS of binary operation.\n\n If the comparison isn't supported, return `NotImplemented` so that the\n "right-hand-side" operation (e.g. `__radd__`) can be tried.\n """\n from narwhals._pandas_like.series import PandasLikeSeries\n\n lhs_index = lhs.native.index\n\n if lhs._broadcast and isinstance(rhs, PandasLikeSeries) and not rhs._broadcast:\n return lhs.native.iloc[0], rhs.native\n\n if isinstance(rhs, PandasLikeSeries):\n if rhs._broadcast:\n return (lhs.native, rhs.native.iloc[0])\n if rhs.native.index is not lhs_index:\n return (\n lhs.native,\n set_index(\n rhs.native,\n lhs_index,\n implementation=rhs._implementation,\n backend_version=rhs._backend_version,\n ),\n )\n return (lhs.native, rhs.native)\n\n if isinstance(rhs, list):\n msg = "Expected Series or scalar, got list."\n raise TypeError(msg)\n # `rhs` must be scalar, so just leave it as-is\n return lhs.native, rhs\n\n\ndef set_index(\n obj: NativeNDFrameT,\n index: Any,\n *,\n implementation: Implementation,\n backend_version: tuple[int, ...],\n) -> NativeNDFrameT:\n """Wrapper around pandas' set_axis to set object index.\n\n We can set `copy` / `inplace` based on implementation/version.\n """\n if isinstance(index, implementation.to_native_namespace().Index) and (\n expected_len := len(index)\n ) != (actual_len := len(obj)):\n msg = f"Expected object of length {expected_len}, got length: {actual_len}"\n raise ShapeError(msg)\n if implementation is Implementation.CUDF:\n obj = obj.copy(deep=False)\n obj.index = index\n return obj\n if implementation is Implementation.PANDAS and (\n (1, 5) <= backend_version < (3,)\n ): # pragma: no cover\n return obj.set_axis(index, axis=0, copy=False)\n else: # pragma: no cover\n return obj.set_axis(index, axis=0)\n\n\ndef rename(\n obj: NativeNDFrameT,\n *args: Any,\n implementation: Implementation,\n backend_version: tuple[int, ...],\n **kwargs: Any,\n) -> NativeNDFrameT:\n """Wrapper around pandas' rename so that we can set `copy` based on implementation/version."""\n if implementation is Implementation.PANDAS and (\n backend_version >= (3,)\n ): # pragma: no cover\n return obj.rename(*args, **kwargs, inplace=False)\n return obj.rename(*args, **kwargs, copy=False, inplace=False)\n\n\n@functools.lru_cache(maxsize=16)\ndef non_object_native_to_narwhals_dtype(native_dtype: Any, version: Version) -> DType: # noqa: C901, PLR0912\n dtype = str(native_dtype)\n\n dtypes = version.dtypes\n if dtype in {"int64", "Int64", "Int64[pyarrow]", "int64[pyarrow]"}:\n return dtypes.Int64()\n if dtype in {"int32", "Int32", "Int32[pyarrow]", "int32[pyarrow]"}:\n return dtypes.Int32()\n if dtype in {"int16", "Int16", "Int16[pyarrow]", "int16[pyarrow]"}:\n return dtypes.Int16()\n if dtype in {"int8", "Int8", "Int8[pyarrow]", "int8[pyarrow]"}:\n return dtypes.Int8()\n if dtype in {"uint64", "UInt64", "UInt64[pyarrow]", "uint64[pyarrow]"}:\n return dtypes.UInt64()\n if dtype in {"uint32", "UInt32", "UInt32[pyarrow]", "uint32[pyarrow]"}:\n return dtypes.UInt32()\n if dtype in {"uint16", "UInt16", "UInt16[pyarrow]", "uint16[pyarrow]"}:\n return dtypes.UInt16()\n if dtype in {"uint8", "UInt8", "UInt8[pyarrow]", "uint8[pyarrow]"}:\n return dtypes.UInt8()\n if dtype in {\n "float64",\n "Float64",\n "Float64[pyarrow]",\n "float64[pyarrow]",\n "double[pyarrow]",\n }:\n return dtypes.Float64()\n if dtype in {\n "float32",\n "Float32",\n "Float32[pyarrow]",\n "float32[pyarrow]",\n "float[pyarrow]",\n }:\n return dtypes.Float32()\n if dtype in {"string", "string[python]", "string[pyarrow]", "large_string[pyarrow]"}:\n return dtypes.String()\n if dtype in {"bool", "boolean", "boolean[pyarrow]", "bool[pyarrow]"}:\n return dtypes.Boolean()\n if dtype.startswith("dictionary<"):\n return dtypes.Categorical()\n if dtype == "category":\n return native_categorical_to_narwhals_dtype(native_dtype, version)\n if (match_ := PATTERN_PD_DATETIME.match(dtype)) or (\n match_ := PATTERN_PA_DATETIME.match(dtype)\n ):\n dt_time_unit: TimeUnit = match_.group("time_unit") # type: ignore[assignment]\n dt_time_zone: str | None = match_.group("time_zone")\n return dtypes.Datetime(dt_time_unit, dt_time_zone)\n if (match_ := PATTERN_PD_DURATION.match(dtype)) or (\n match_ := PATTERN_PA_DURATION.match(dtype)\n ):\n du_time_unit: TimeUnit = match_.group("time_unit") # type: ignore[assignment]\n return dtypes.Duration(du_time_unit)\n if dtype == "date32[day][pyarrow]":\n return dtypes.Date()\n if dtype.startswith("decimal") and dtype.endswith("[pyarrow]"):\n return dtypes.Decimal()\n if dtype.startswith("time") and dtype.endswith("[pyarrow]"):\n return dtypes.Time()\n if dtype.startswith("binary") and dtype.endswith("[pyarrow]"):\n return dtypes.Binary()\n return dtypes.Unknown() # pragma: no cover\n\n\ndef object_native_to_narwhals_dtype(\n series: PandasLikeSeries, version: Version, implementation: Implementation\n) -> DType:\n dtypes = version.dtypes\n if implementation is Implementation.CUDF:\n # Per conversations with their maintainers, they don't support arbitrary\n # objects, so we can just return String.\n return dtypes.String()\n\n # Arbitrary limit of 100 elements to use to sniff dtype.\n inferred_dtype = pd.api.types.infer_dtype(series.head(100), skipna=True)\n if inferred_dtype == "string":\n return dtypes.String()\n if inferred_dtype == "empty" and version is not Version.V1:\n # Default to String for empty Series.\n return dtypes.String()\n elif inferred_dtype == "empty":\n # But preserve returning Object in V1.\n return dtypes.Object()\n return dtypes.Object()\n\n\ndef native_categorical_to_narwhals_dtype(\n native_dtype: pd.CategoricalDtype,\n version: Version,\n implementation: Literal[Implementation.CUDF] | None = None,\n) -> DType:\n dtypes = version.dtypes\n if version is Version.V1:\n return dtypes.Categorical()\n if native_dtype.ordered:\n into_iter = (\n _cudf_categorical_to_list(native_dtype)\n if implementation is Implementation.CUDF\n else native_dtype.categories.to_list\n )\n return dtypes.Enum(_DeferredIterable(into_iter))\n return dtypes.Categorical()\n\n\ndef _cudf_categorical_to_list(\n native_dtype: Any,\n) -> Callable[[], list[Any]]: # pragma: no cover\n # NOTE: https://docs.rapids.ai/api/cudf/stable/user_guide/api_docs/api/cudf.core.dtypes.categoricaldtype/#cudf.core.dtypes.CategoricalDtype\n def fn() -> list[Any]:\n return native_dtype.categories.to_arrow().to_pylist()\n\n return fn\n\n\ndef native_to_narwhals_dtype(\n native_dtype: Any, version: Version, implementation: Implementation\n) -> DType:\n str_dtype = str(native_dtype)\n\n if str_dtype.startswith(("large_list", "list", "struct", "fixed_size_list")):\n from narwhals._arrow.utils import (\n native_to_narwhals_dtype as arrow_native_to_narwhals_dtype,\n )\n\n if hasattr(native_dtype, "to_arrow"): # pragma: no cover\n # cudf, cudf.pandas\n return arrow_native_to_narwhals_dtype(native_dtype.to_arrow(), version)\n return arrow_native_to_narwhals_dtype(native_dtype.pyarrow_dtype, version)\n if str_dtype == "category" and implementation.is_cudf():\n # https://github.com/rapidsai/cudf/issues/18536\n # https://github.com/rapidsai/cudf/issues/14027\n return native_categorical_to_narwhals_dtype(\n native_dtype, version, Implementation.CUDF\n )\n if str_dtype != "object":\n return non_object_native_to_narwhals_dtype(native_dtype, version)\n elif implementation is Implementation.DASK:\n # Per conversations with their maintainers, they don't support arbitrary\n # objects, so we can just return String.\n return version.dtypes.String()\n msg = (\n "Unreachable code, object dtype should be handled separately" # pragma: no cover\n )\n raise AssertionError(msg)\n\n\nif Implementation.PANDAS._backend_version() >= (1, 2):\n\n def is_dtype_numpy_nullable(dtype: Any) -> TypeIs[BaseMaskedDtype]:\n """Return `True` if `dtype` is `"numpy_nullable"`."""\n # NOTE: We need a sentinel as the positive case is `BaseMaskedDtype.base = None`\n # See https://github.com/narwhals-dev/narwhals/pull/2740#discussion_r2171667055\n sentinel = object()\n return (\n isinstance(dtype, pd.api.extensions.ExtensionDtype)\n and getattr(dtype, "base", sentinel) is None\n )\nelse: # pragma: no cover\n\n def is_dtype_numpy_nullable(dtype: Any) -> TypeIs[BaseMaskedDtype]:\n # NOTE: `base` attribute was added between 1.1-1.2\n # Checking by isinstance requires using an import path that is no longer valid\n # `1.1`: https://github.com/pandas-dev/pandas/blob/b5958ee1999e9aead1938c0bba2b674378807b3d/pandas/core/arrays/masked.py#L37\n # `1.2`: https://github.com/pandas-dev/pandas/blob/7c48ff4409c622c582c56a5702373f726de08e96/pandas/core/arrays/masked.py#L41\n # `1.5`: https://github.com/pandas-dev/pandas/blob/35b0d1dcadf9d60722c055ee37442dc76a29e64c/pandas/core/dtypes/dtypes.py#L1609\n if isinstance(dtype, pd.api.extensions.ExtensionDtype):\n from pandas.core.arrays.masked import ( # type: ignore[attr-defined]\n BaseMaskedDtype as OldBaseMaskedDtype, # pyright: ignore[reportAttributeAccessIssue]\n )\n\n return isinstance(dtype, OldBaseMaskedDtype)\n return False\n\n\ndef get_dtype_backend(dtype: Any, implementation: Implementation) -> DTypeBackend:\n """Get dtype backend for pandas type.\n\n Matches pandas' `dtype_backend` argument in `convert_dtypes`.\n """\n if implementation is Implementation.CUDF:\n return None\n if is_dtype_pyarrow(dtype):\n return "pyarrow"\n return "numpy_nullable" if is_dtype_numpy_nullable(dtype) else None\n\n\n@functools.lru_cache(maxsize=16)\ndef is_dtype_pyarrow(dtype: Any) -> TypeIs[pd.ArrowDtype]:\n return hasattr(pd, "ArrowDtype") and isinstance(dtype, pd.ArrowDtype)\n\n\ndef narwhals_to_native_dtype( # noqa: C901, PLR0912, PLR0915\n dtype: IntoDType,\n dtype_backend: DTypeBackend,\n implementation: Implementation,\n backend_version: tuple[int, ...],\n version: Version,\n) -> str | PandasDtype:\n if dtype_backend is not None and dtype_backend not in {"pyarrow", "numpy_nullable"}:\n msg = f"Expected one of {{None, 'pyarrow', 'numpy_nullable'}}, got: '{dtype_backend}'"\n raise ValueError(msg)\n dtypes = version.dtypes\n if isinstance_or_issubclass(dtype, dtypes.Decimal):\n msg = "Casting to Decimal is not supported yet."\n raise NotImplementedError(msg)\n if isinstance_or_issubclass(dtype, dtypes.Float64):\n if dtype_backend == "pyarrow":\n return "Float64[pyarrow]"\n elif dtype_backend == "numpy_nullable":\n return "Float64"\n return "float64"\n if isinstance_or_issubclass(dtype, dtypes.Float32):\n if dtype_backend == "pyarrow":\n return "Float32[pyarrow]"\n elif dtype_backend == "numpy_nullable":\n return "Float32"\n return "float32"\n if isinstance_or_issubclass(dtype, dtypes.Int64):\n if dtype_backend == "pyarrow":\n return "Int64[pyarrow]"\n elif dtype_backend == "numpy_nullable":\n return "Int64"\n return "int64"\n if isinstance_or_issubclass(dtype, dtypes.Int32):\n if dtype_backend == "pyarrow":\n return "Int32[pyarrow]"\n elif dtype_backend == "numpy_nullable":\n return "Int32"\n return "int32"\n if isinstance_or_issubclass(dtype, dtypes.Int16):\n if dtype_backend == "pyarrow":\n return "Int16[pyarrow]"\n elif dtype_backend == "numpy_nullable":\n return "Int16"\n return "int16"\n if isinstance_or_issubclass(dtype, dtypes.Int8):\n if dtype_backend == "pyarrow":\n return "Int8[pyarrow]"\n elif dtype_backend == "numpy_nullable":\n return "Int8"\n return "int8"\n if isinstance_or_issubclass(dtype, dtypes.UInt64):\n if dtype_backend == "pyarrow":\n return "UInt64[pyarrow]"\n elif dtype_backend == "numpy_nullable":\n return "UInt64"\n return "uint64"\n if isinstance_or_issubclass(dtype, dtypes.UInt32):\n if dtype_backend == "pyarrow":\n return "UInt32[pyarrow]"\n elif dtype_backend == "numpy_nullable":\n return "UInt32"\n return "uint32"\n if isinstance_or_issubclass(dtype, dtypes.UInt16):\n if dtype_backend == "pyarrow":\n return "UInt16[pyarrow]"\n elif dtype_backend == "numpy_nullable":\n return "UInt16"\n return "uint16"\n if isinstance_or_issubclass(dtype, dtypes.UInt8):\n if dtype_backend == "pyarrow":\n return "UInt8[pyarrow]"\n elif dtype_backend == "numpy_nullable":\n return "UInt8"\n return "uint8"\n if isinstance_or_issubclass(dtype, dtypes.String):\n if dtype_backend == "pyarrow":\n return "string[pyarrow]"\n elif dtype_backend == "numpy_nullable":\n return "string"\n return str\n if isinstance_or_issubclass(dtype, dtypes.Boolean):\n if dtype_backend == "pyarrow":\n return "boolean[pyarrow]"\n elif dtype_backend == "numpy_nullable":\n return "boolean"\n return "bool"\n if isinstance_or_issubclass(dtype, dtypes.Categorical):\n # TODO(Unassigned): is there no pyarrow-backed categorical?\n # or at least, convert_dtypes(dtype_backend='pyarrow') doesn't\n # convert to it?\n return "category"\n if isinstance_or_issubclass(dtype, dtypes.Datetime):\n # Pandas does not support "ms" or "us" time units before version 2.0\n if implementation is Implementation.PANDAS and backend_version < (\n 2,\n ): # pragma: no cover\n dt_time_unit = "ns"\n else:\n dt_time_unit = dtype.time_unit\n\n if dtype_backend == "pyarrow":\n tz_part = f", tz={tz}" if (tz := dtype.time_zone) else ""\n return f"timestamp[{dt_time_unit}{tz_part}][pyarrow]"\n else:\n tz_part = f", {tz}" if (tz := dtype.time_zone) else ""\n return f"datetime64[{dt_time_unit}{tz_part}]"\n if isinstance_or_issubclass(dtype, dtypes.Duration):\n if implementation is Implementation.PANDAS and backend_version < (\n 2,\n ): # pragma: no cover\n du_time_unit = "ns"\n else:\n du_time_unit = dtype.time_unit\n return (\n f"duration[{du_time_unit}][pyarrow]"\n if dtype_backend == "pyarrow"\n else f"timedelta64[{du_time_unit}]"\n )\n if isinstance_or_issubclass(dtype, dtypes.Date):\n try:\n import pyarrow as pa # ignore-banned-import\n except ModuleNotFoundError: # pragma: no cover\n msg = "'pyarrow>=11.0.0' is required for `Date` dtype."\n return "date32[pyarrow]"\n if isinstance_or_issubclass(dtype, dtypes.Enum):\n if version is Version.V1:\n msg = "Converting to Enum is not supported in narwhals.stable.v1"\n raise NotImplementedError(msg)\n if isinstance(dtype, dtypes.Enum):\n ns = implementation.to_native_namespace()\n return ns.CategoricalDtype(dtype.categories, ordered=True)\n msg = "Can not cast / initialize Enum without categories present"\n raise ValueError(msg)\n\n if isinstance_or_issubclass(\n dtype, (dtypes.Struct, dtypes.Array, dtypes.List, dtypes.Time, dtypes.Binary)\n ):\n if implementation is Implementation.PANDAS and backend_version >= (2, 2):\n try:\n import pandas as pd\n import pyarrow as pa # ignore-banned-import # noqa: F401\n except ImportError as exc: # pragma: no cover\n msg = f"Unable to convert to {dtype} to to the following exception: {exc.msg}"\n raise ImportError(msg) from exc\n from narwhals._arrow.utils import (\n narwhals_to_native_dtype as arrow_narwhals_to_native_dtype,\n )\n\n return pd.ArrowDtype(arrow_narwhals_to_native_dtype(dtype, version=version))\n else: # pragma: no cover\n msg = (\n f"Converting to {dtype} dtype is not supported for implementation "\n f"{implementation} and version {version}."\n )\n raise NotImplementedError(msg)\n msg = f"Unknown dtype: {dtype}" # pragma: no cover\n raise AssertionError(msg)\n\n\ndef int_dtype_mapper(dtype: Any) -> str:\n if "pyarrow" in str(dtype):\n return "Int64[pyarrow]"\n if str(dtype).lower() != str(dtype): # pragma: no cover\n return "Int64"\n return "int64"\n\n\ndef calculate_timestamp_datetime( # noqa: C901, PLR0912\n s: NativeSeriesT, original_time_unit: str, time_unit: str\n) -> NativeSeriesT:\n if original_time_unit == "ns":\n if time_unit == "ns":\n result = s\n elif time_unit == "us":\n result = s // 1_000\n else:\n result = s // 1_000_000\n elif original_time_unit == "us":\n if time_unit == "ns":\n result = s * NS_PER_MICROSECOND\n elif time_unit == "us":\n result = s\n else:\n result = s // 1_000\n elif original_time_unit == "ms":\n if time_unit == "ns":\n result = s * NS_PER_MILLISECOND\n elif time_unit == "us":\n result = s * 1_000\n else:\n result = s\n elif original_time_unit == "s":\n if time_unit == "ns":\n result = s * NS_PER_SECOND\n elif time_unit == "us":\n result = s * US_PER_SECOND\n else:\n result = s * MS_PER_SECOND\n else: # pragma: no cover\n msg = f"unexpected time unit {original_time_unit}, please report a bug at https://github.com/narwhals-dev/narwhals"\n raise AssertionError(msg)\n return result\n\n\ndef calculate_timestamp_date(s: NativeSeriesT, time_unit: str) -> NativeSeriesT:\n s = s * SECONDS_PER_DAY\n if time_unit == "ns":\n result = s * NS_PER_SECOND\n elif time_unit == "us":\n result = s * US_PER_SECOND\n else:\n result = s * MS_PER_SECOND\n return result\n\n\ndef select_columns_by_name(\n df: NativeDataFrameT,\n column_names: list[str] | _1DArray, # NOTE: Cannot be a tuple!\n backend_version: tuple[int, ...],\n implementation: Implementation,\n) -> NativeDataFrameT | Any:\n """Select columns by name.\n\n Prefer this over `df.loc[:, column_names]` as it's\n generally more performant.\n """\n if len(column_names) == df.shape[1] and (df.columns == column_names).all():\n return df\n if (df.columns.dtype.kind == "b") or (\n implementation is Implementation.PANDAS and backend_version < (1, 5)\n ):\n # See https://github.com/narwhals-dev/narwhals/issues/1349#issuecomment-2470118122\n # for why we need this\n if error := check_columns_exist(column_names, available=df.columns.tolist()):\n raise error\n return df.loc[:, column_names]\n try:\n return df[column_names]\n except KeyError as e:\n if error := check_columns_exist(column_names, available=df.columns.tolist()):\n raise error from e\n raise\n\n\ndef is_non_nullable_boolean(s: PandasLikeSeries) -> bool:\n # cuDF booleans are nullable but the native dtype is still 'bool'.\n return (\n s._implementation\n in {Implementation.PANDAS, Implementation.MODIN, Implementation.DASK}\n and s.native.dtype == "bool"\n )\n\n\ndef import_array_module(implementation: Implementation, /) -> ModuleType:\n """Returns numpy or cupy module depending on the given implementation."""\n if implementation in {Implementation.PANDAS, Implementation.MODIN}:\n import numpy as np\n\n return np\n elif implementation is Implementation.CUDF:\n import cupy as cp # ignore-banned-import # cuDF dependency.\n\n return cp\n else: # pragma: no cover\n msg = f"Expected pandas/modin/cudf, got: {implementation}"\n raise AssertionError(msg)\n\n\nclass PandasLikeSeriesNamespace(EagerSeriesNamespace["PandasLikeSeries", Any]):\n @property\n def implementation(self) -> Implementation:\n return self.compliant._implementation\n\n @property\n def backend_version(self) -> tuple[int, ...]:\n return self.compliant._backend_version\n\n @property\n def version(self) -> Version:\n return self.compliant._version\n | .venv\Lib\site-packages\narwhals\_pandas_like\utils.py | utils.py | Python | 25,428 | 0.95 | 0.215596 | 0.049828 | awesome-app | 336 | 2024-03-02T09:29:24.184814 | Apache-2.0 | false | fd78d5924c2afe29ef2547289dc8ba93 |
\n\n | .venv\Lib\site-packages\narwhals\_pandas_like\__pycache__\dataframe.cpython-313.pyc | dataframe.cpython-313.pyc | Other | 55,818 | 0.75 | 0.010657 | 0.011342 | python-kit | 838 | 2024-04-06T01:23:58.973478 | GPL-3.0 | false | b984cead7b564d935f3aad10f8f9997a |
\n\n | .venv\Lib\site-packages\narwhals\_pandas_like\__pycache__\expr.cpython-313.pyc | expr.cpython-313.pyc | Other | 17,163 | 0.95 | 0.010309 | 0 | vue-tools | 670 | 2024-03-24T19:31:31.912898 | MIT | false | 07b8f1272a6b6aacf437ff24816ea3e4 |
\n\n | .venv\Lib\site-packages\narwhals\_pandas_like\__pycache__\group_by.cpython-313.pyc | group_by.cpython-313.pyc | Other | 13,810 | 0.95 | 0.008475 | 0 | awesome-app | 752 | 2025-04-23T01:43:11.012191 | GPL-3.0 | false | 7998b2b1276523a7dfbbfaec002d1a02 |
\n\n | .venv\Lib\site-packages\narwhals\_pandas_like\__pycache__\namespace.cpython-313.pyc | namespace.cpython-313.pyc | Other | 25,004 | 0.95 | 0.011561 | 0.011834 | react-lib | 625 | 2024-03-12T19:10:28.754595 | GPL-3.0 | false | 74815880b674c023c1cbcf8f78732b72 |
\n\n | .venv\Lib\site-packages\narwhals\_pandas_like\__pycache__\selectors.cpython-313.pyc | selectors.cpython-313.pyc | Other | 1,953 | 0.95 | 0 | 0 | node-utils | 975 | 2023-07-21T11:10:20.052197 | Apache-2.0 | false | e62b36fe41451d2c3e0d5f3b7495efa2 |
\n\n | .venv\Lib\site-packages\narwhals\_pandas_like\__pycache__\series.cpython-313.pyc | series.cpython-313.pyc | Other | 59,672 | 0.75 | 0.010638 | 0.014085 | node-utils | 101 | 2024-08-17T04:44:31.880042 | BSD-3-Clause | false | ca3968a03d6168c91d5f2280401c00d9 |
\n\n | .venv\Lib\site-packages\narwhals\_pandas_like\__pycache__\series_cat.cpython-313.pyc | series_cat.cpython-313.pyc | Other | 1,227 | 0.7 | 0 | 0 | python-kit | 137 | 2024-02-28T01:18:15.328527 | Apache-2.0 | false | 25b87bfb5abbc3943c11c9e8f9c4b9bd |
\n\n | .venv\Lib\site-packages\narwhals\_pandas_like\__pycache__\series_dt.cpython-313.pyc | series_dt.cpython-313.pyc | Other | 16,026 | 0.8 | 0.030612 | 0 | react-lib | 161 | 2024-07-17T14:20:12.634487 | MIT | false | ff6613db9372cb590d8596920344267c |
\n\n | .venv\Lib\site-packages\narwhals\_pandas_like\__pycache__\series_list.cpython-313.pyc | series_list.cpython-313.pyc | Other | 1,921 | 0.8 | 0 | 0 | python-kit | 9 | 2024-02-22T15:23:02.731395 | Apache-2.0 | false | 8b75412aa01b135b593ee049522dac9f |
\n\n | .venv\Lib\site-packages\narwhals\_pandas_like\__pycache__\series_str.cpython-313.pyc | series_str.cpython-313.pyc | Other | 7,412 | 0.95 | 0 | 0.025 | node-utils | 997 | 2023-10-19T15:06:24.472939 | Apache-2.0 | false | 869317becdd542a17502fa3b823f9ea3 |
\n\n | .venv\Lib\site-packages\narwhals\_pandas_like\__pycache__\series_struct.cpython-313.pyc | series_struct.cpython-313.pyc | Other | 1,204 | 0.8 | 0 | 0 | awesome-app | 905 | 2025-05-29T15:23:58.010382 | Apache-2.0 | false | 947d561533e5288e6a99e0d547ffa178 |
\n\n | .venv\Lib\site-packages\narwhals\_pandas_like\__pycache__\typing.cpython-313.pyc | typing.cpython-313.pyc | Other | 1,171 | 0.7 | 0 | 0 | awesome-app | 258 | 2024-10-28T17:33:52.402900 | BSD-3-Clause | false | 4a362e09dba9a1fe71f94efd27e5b6c1 |
\n\n | .venv\Lib\site-packages\narwhals\_pandas_like\__pycache__\utils.cpython-313.pyc | utils.cpython-313.pyc | Other | 27,343 | 0.95 | 0.057018 | 0.009479 | vue-tools | 122 | 2024-04-15T04:38:33.387143 | MIT | false | c9714079a6b7de4b7c8b5390bf47ff3d |
\n\n | .venv\Lib\site-packages\narwhals\_pandas_like\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 196 | 0.7 | 0 | 0 | awesome-app | 267 | 2024-09-20T12:56:37.292729 | BSD-3-Clause | false | dcb9bbf4243e332d37a98282cc95b572 |
from __future__ import annotations\n\nfrom collections.abc import Iterator, Mapping, Sequence, Sized\nfrom typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar, cast, overload\n\nimport polars as pl\n\nfrom narwhals._polars.namespace import PolarsNamespace\nfrom narwhals._polars.series import PolarsSeries\nfrom narwhals._polars.utils import (\n catch_polars_exception,\n extract_args_kwargs,\n native_to_narwhals_dtype,\n)\nfrom narwhals._utils import (\n Implementation,\n _into_arrow_table,\n check_columns_exist,\n convert_str_slice_to_int_slice,\n is_compliant_series,\n is_index_selector,\n is_range,\n is_sequence_like,\n is_slice_index,\n is_slice_none,\n parse_columns_to_drop,\n parse_version,\n requires,\n validate_backend_version,\n)\nfrom narwhals.dependencies import is_numpy_array_1d\nfrom narwhals.exceptions import ColumnNotFoundError\n\nif TYPE_CHECKING:\n from types import ModuleType\n from typing import Callable\n\n import pandas as pd\n import pyarrow as pa\n from typing_extensions import Self, TypeAlias, TypeIs\n\n from narwhals._compliant.typing import CompliantDataFrameAny, CompliantLazyFrameAny\n from narwhals._polars.expr import PolarsExpr\n from narwhals._polars.group_by import PolarsGroupBy, PolarsLazyGroupBy\n from narwhals._translate import IntoArrowTable\n from narwhals._utils import Version, _FullContext\n from narwhals.dataframe import DataFrame, LazyFrame\n from narwhals.dtypes import DType\n from narwhals.schema import Schema\n from narwhals.typing import (\n JoinStrategy,\n MultiColSelector,\n MultiIndexSelector,\n PivotAgg,\n SingleIndexSelector,\n _2DArray,\n )\n\n T = TypeVar("T")\n R = TypeVar("R")\n\nMethod: TypeAlias = "Callable[..., R]"\n"""Generic alias representing all methods implemented via `__getattr__`.\n\nWhere `R` is the return type.\n"""\n\n# DataFrame methods where PolarsDataFrame just defers to Polars.DataFrame directly.\nINHERITED_METHODS = frozenset(\n [\n "clone",\n "drop_nulls",\n "estimated_size",\n "explode",\n "filter",\n "gather_every",\n "head",\n "is_unique",\n "item",\n "iter_rows",\n "join_asof",\n "rename",\n "row",\n "rows",\n "sample",\n "select",\n "sort",\n "tail",\n "to_arrow",\n "to_pandas",\n "unique",\n "with_columns",\n "write_csv",\n "write_parquet",\n ]\n)\n\nNativePolarsFrame = TypeVar("NativePolarsFrame", pl.DataFrame, pl.LazyFrame)\n\n\nclass PolarsBaseFrame(Generic[NativePolarsFrame]):\n drop_nulls: Method[Self]\n explode: Method[Self]\n filter: Method[Self]\n gather_every: Method[Self]\n head: Method[Self]\n join_asof: Method[Self]\n rename: Method[Self]\n select: Method[Self]\n sort: Method[Self]\n tail: Method[Self]\n unique: Method[Self]\n with_columns: Method[Self]\n\n def __init__(\n self, df: NativePolarsFrame, *, backend_version: tuple[int, ...], version: Version\n ) -> None:\n self._native_frame: NativePolarsFrame = df\n self._backend_version = backend_version\n self._implementation = Implementation.POLARS\n self._version = version\n validate_backend_version(self._implementation, self._backend_version)\n\n @property\n def native(self) -> NativePolarsFrame:\n return self._native_frame\n\n @property\n def columns(self) -> list[str]:\n return self.native.columns\n\n def __narwhals_namespace__(self) -> PolarsNamespace:\n return PolarsNamespace(\n backend_version=self._backend_version, version=self._version\n )\n\n def __native_namespace__(self) -> ModuleType:\n if self._implementation is Implementation.POLARS:\n return self._implementation.to_native_namespace()\n\n msg = f"Expected polars, got: {type(self._implementation)}" # pragma: no cover\n raise AssertionError(msg)\n\n def _with_native(self, df: NativePolarsFrame) -> Self:\n return self.__class__(\n df, backend_version=self._backend_version, version=self._version\n )\n\n def _with_version(self, version: Version) -> Self:\n return self.__class__(\n self.native, backend_version=self._backend_version, version=version\n )\n\n @classmethod\n def from_native(cls, data: NativePolarsFrame, /, *, context: _FullContext) -> Self:\n return cls(\n data, backend_version=context._backend_version, version=context._version\n )\n\n def _check_columns_exist(self, subset: Sequence[str]) -> ColumnNotFoundError | None:\n return check_columns_exist( # pragma: no cover\n subset, available=self.columns\n )\n\n def simple_select(self, *column_names: str) -> Self:\n return self._with_native(self.native.select(*column_names))\n\n def aggregate(self, *exprs: Any) -> Self:\n return self.select(*exprs)\n\n @property\n def schema(self) -> dict[str, DType]:\n return {\n name: native_to_narwhals_dtype(dtype, self._version, self._backend_version)\n for name, dtype in self.native.schema.items()\n }\n\n def join(\n self,\n other: Self,\n *,\n how: JoinStrategy,\n left_on: Sequence[str] | None,\n right_on: Sequence[str] | None,\n suffix: str,\n ) -> Self:\n how_native = (\n "outer" if (self._backend_version < (0, 20, 29) and how == "full") else how\n )\n return self._with_native(\n self.native.join(\n other=other.native,\n how=how_native, # type: ignore[arg-type]\n left_on=left_on,\n right_on=right_on,\n suffix=suffix,\n )\n )\n\n def unpivot(\n self,\n on: Sequence[str] | None,\n index: Sequence[str] | None,\n variable_name: str,\n value_name: str,\n ) -> Self:\n if self._backend_version < (1, 0, 0):\n return self._with_native(\n self.native.melt(\n id_vars=index,\n value_vars=on,\n variable_name=variable_name,\n value_name=value_name,\n )\n )\n return self._with_native(\n self.native.unpivot(\n on=on, index=index, variable_name=variable_name, value_name=value_name\n )\n )\n\n def collect_schema(self) -> dict[str, DType]:\n if self._backend_version < (1,):\n return {\n name: native_to_narwhals_dtype(\n dtype, self._version, self._backend_version\n )\n for name, dtype in self.native.schema.items()\n }\n else:\n collected_schema = self.native.collect_schema()\n return {\n name: native_to_narwhals_dtype(\n dtype, self._version, self._backend_version\n )\n for name, dtype in collected_schema.items()\n }\n\n def with_row_index(self, name: str, order_by: Sequence[str] | None) -> Self:\n frame = self.native\n if order_by is None:\n result = frame.with_row_index(name)\n else:\n end = pl.count() if self._backend_version < (0, 20, 5) else pl.len()\n result = frame.select(\n pl.int_range(start=0, end=end).sort_by(order_by).alias(name), pl.all()\n )\n\n return self._with_native(result)\n\n\nclass PolarsDataFrame(PolarsBaseFrame[pl.DataFrame]):\n clone: Method[Self]\n collect: Method[CompliantDataFrameAny]\n estimated_size: Method[int | float]\n gather_every: Method[Self]\n item: Method[Any]\n iter_rows: Method[Iterator[tuple[Any, ...]] | Iterator[Mapping[str, Any]]]\n is_unique: Method[PolarsSeries]\n row: Method[tuple[Any, ...]]\n rows: Method[Sequence[tuple[Any, ...]] | Sequence[Mapping[str, Any]]]\n sample: Method[Self]\n to_arrow: Method[pa.Table]\n to_pandas: Method[pd.DataFrame]\n # NOTE: `write_csv` requires an `@overload` for `str | None`\n # Can't do that here 😟\n write_csv: Method[Any]\n write_parquet: Method[None]\n\n # CompliantDataFrame\n _evaluate_aliases: Any\n\n @classmethod\n def from_arrow(cls, data: IntoArrowTable, /, *, context: _FullContext) -> Self:\n if context._backend_version >= (1, 3):\n native = pl.DataFrame(data)\n else:\n native = cast("pl.DataFrame", pl.from_arrow(_into_arrow_table(data, context)))\n return cls.from_native(native, context=context)\n\n @classmethod\n def from_dict(\n cls,\n data: Mapping[str, Any],\n /,\n *,\n context: _FullContext,\n schema: Mapping[str, DType] | Schema | None,\n ) -> Self:\n from narwhals.schema import Schema\n\n pl_schema = Schema(schema).to_polars() if schema is not None else schema\n return cls.from_native(pl.from_dict(data, pl_schema), context=context)\n\n @staticmethod\n def _is_native(obj: pl.DataFrame | Any) -> TypeIs[pl.DataFrame]:\n return isinstance(obj, pl.DataFrame)\n\n @classmethod\n def from_numpy(\n cls,\n data: _2DArray,\n /,\n *,\n context: _FullContext, # NOTE: Maybe only `Implementation`?\n schema: Mapping[str, DType] | Schema | Sequence[str] | None,\n ) -> Self:\n from narwhals.schema import Schema\n\n pl_schema = (\n Schema(schema).to_polars()\n if isinstance(schema, (Mapping, Schema))\n else schema\n )\n return cls.from_native(pl.from_numpy(data, pl_schema), context=context)\n\n def to_narwhals(self) -> DataFrame[pl.DataFrame]:\n return self._version.dataframe(self, level="full")\n\n def __repr__(self) -> str: # pragma: no cover\n return "PolarsDataFrame"\n\n def __narwhals_dataframe__(self) -> Self:\n return self\n\n @overload\n def _from_native_object(self, obj: pl.Series) -> PolarsSeries: ...\n\n @overload\n def _from_native_object(self, obj: pl.DataFrame) -> Self: ...\n\n @overload\n def _from_native_object(self, obj: T) -> T: ...\n\n def _from_native_object(\n self, obj: pl.Series | pl.DataFrame | T\n ) -> Self | PolarsSeries | T:\n if isinstance(obj, pl.Series):\n return PolarsSeries.from_native(obj, context=self)\n if self._is_native(obj):\n return self._with_native(obj)\n # scalar\n return obj\n\n def __len__(self) -> int:\n return len(self.native)\n\n def __getattr__(self, attr: str) -> Any:\n if attr not in INHERITED_METHODS: # pragma: no cover\n msg = f"{self.__class__.__name__} has not attribute '{attr}'."\n raise AttributeError(msg)\n\n def func(*args: Any, **kwargs: Any) -> Any:\n pos, kwds = extract_args_kwargs(args, kwargs)\n try:\n return self._from_native_object(getattr(self.native, attr)(*pos, **kwds))\n except pl.exceptions.ColumnNotFoundError as e: # pragma: no cover\n msg = f"{e!s}\n\nHint: Did you mean one of these columns: {self.columns}?"\n raise ColumnNotFoundError(msg) from e\n except Exception as e: # noqa: BLE001\n raise catch_polars_exception(e, self._backend_version) from None\n\n return func\n\n def __array__(\n self, dtype: Any | None = None, *, copy: bool | None = None\n ) -> _2DArray:\n if self._backend_version < (0, 20, 28) and copy is not None:\n msg = "`copy` in `__array__` is only supported for 'polars>=0.20.28'"\n raise NotImplementedError(msg)\n if self._backend_version < (0, 20, 28):\n return self.native.__array__(dtype)\n return self.native.__array__(dtype)\n\n def to_numpy(self, dtype: Any = None, *, copy: bool | None = None) -> _2DArray:\n return self.native.to_numpy()\n\n @property\n def shape(self) -> tuple[int, int]:\n return self.native.shape\n\n def __getitem__( # noqa: C901, PLR0912\n self,\n item: tuple[\n SingleIndexSelector | MultiIndexSelector[PolarsSeries],\n MultiColSelector[PolarsSeries],\n ],\n ) -> Any:\n rows, columns = item\n if self._backend_version > (0, 20, 30):\n rows_native = rows.native if is_compliant_series(rows) else rows\n columns_native = columns.native if is_compliant_series(columns) else columns\n selector = rows_native, columns_native\n selected = self.native.__getitem__(selector) # type: ignore[index]\n return self._from_native_object(selected)\n else: # pragma: no cover\n # TODO(marco): we can delete this branch after Polars==0.20.30 becomes the minimum\n # Polars version we support\n # This mostly mirrors the logic in `EagerDataFrame.__getitem__`.\n rows = list(rows) if isinstance(rows, tuple) else rows\n columns = list(columns) if isinstance(columns, tuple) else columns\n if is_numpy_array_1d(columns):\n columns = columns.tolist()\n\n native = self.native\n if not is_slice_none(columns):\n if isinstance(columns, Sized) and len(columns) == 0:\n return self.select()\n if is_index_selector(columns):\n if is_slice_index(columns) or is_range(columns):\n native = native.select(\n self.columns[slice(columns.start, columns.stop, columns.step)]\n )\n elif is_compliant_series(columns):\n native = native[:, columns.native.to_list()]\n else:\n native = native[:, columns]\n elif isinstance(columns, slice):\n native = native.select(\n self.columns[\n slice(*convert_str_slice_to_int_slice(columns, self.columns))\n ]\n )\n elif is_compliant_series(columns):\n native = native.select(columns.native.to_list())\n elif is_sequence_like(columns):\n native = native.select(columns)\n else:\n msg = f"Unreachable code, got unexpected type: {type(columns)}"\n raise AssertionError(msg)\n\n if not is_slice_none(rows):\n if isinstance(rows, int):\n native = native[[rows], :]\n elif isinstance(rows, (slice, range)):\n native = native[rows, :]\n elif is_compliant_series(rows):\n native = native[rows.native, :]\n elif is_sequence_like(rows):\n native = native[rows, :]\n else:\n msg = f"Unreachable code, got unexpected type: {type(rows)}"\n raise AssertionError(msg)\n\n return self._with_native(native)\n\n def get_column(self, name: str) -> PolarsSeries:\n return PolarsSeries.from_native(self.native.get_column(name), context=self)\n\n def iter_columns(self) -> Iterator[PolarsSeries]:\n for series in self.native.iter_columns():\n yield PolarsSeries.from_native(series, context=self)\n\n def lazy(self, *, backend: Implementation | None = None) -> CompliantLazyFrameAny:\n if backend is None or backend is Implementation.POLARS:\n return PolarsLazyFrame.from_native(self.native.lazy(), context=self)\n elif backend is Implementation.DUCKDB:\n import duckdb # ignore-banned-import\n\n from narwhals._duckdb.dataframe import DuckDBLazyFrame\n\n # NOTE: (F841) is a false positive\n df = self.native # noqa: F841\n return DuckDBLazyFrame(\n duckdb.table("df"),\n backend_version=parse_version(duckdb),\n version=self._version,\n )\n elif backend is Implementation.DASK:\n import dask # ignore-banned-import\n import dask.dataframe as dd # ignore-banned-import\n\n from narwhals._dask.dataframe import DaskLazyFrame\n\n return DaskLazyFrame(\n dd.from_pandas(self.native.to_pandas()),\n backend_version=parse_version(dask),\n version=self._version,\n )\n raise AssertionError # pragma: no cover\n\n @overload\n def to_dict(self, *, as_series: Literal[True]) -> dict[str, PolarsSeries]: ...\n\n @overload\n def to_dict(self, *, as_series: Literal[False]) -> dict[str, list[Any]]: ...\n\n def to_dict(\n self, *, as_series: bool\n ) -> dict[str, PolarsSeries] | dict[str, list[Any]]:\n if as_series:\n return {\n name: PolarsSeries.from_native(col, context=self)\n for name, col in self.native.to_dict().items()\n }\n else:\n return self.native.to_dict(as_series=False)\n\n def group_by(\n self, keys: Sequence[str] | Sequence[PolarsExpr], *, drop_null_keys: bool\n ) -> PolarsGroupBy:\n from narwhals._polars.group_by import PolarsGroupBy\n\n return PolarsGroupBy(self, keys, drop_null_keys=drop_null_keys)\n\n def drop(self, columns: Sequence[str], *, strict: bool) -> Self:\n to_drop = parse_columns_to_drop(self, columns, strict=strict)\n return self._with_native(self.native.drop(to_drop))\n\n @requires.backend_version((1,))\n def pivot(\n self,\n on: Sequence[str],\n *,\n index: Sequence[str] | None,\n values: Sequence[str] | None,\n aggregate_function: PivotAgg | None,\n sort_columns: bool,\n separator: str,\n ) -> Self:\n try:\n result = self.native.pivot(\n on,\n index=index,\n values=values,\n aggregate_function=aggregate_function,\n sort_columns=sort_columns,\n separator=separator,\n )\n except Exception as e: # noqa: BLE001\n raise catch_polars_exception(e, self._backend_version) from None\n return self._from_native_object(result)\n\n def to_polars(self) -> pl.DataFrame:\n return self.native\n\n def join(\n self,\n other: Self,\n *,\n how: JoinStrategy,\n left_on: Sequence[str] | None,\n right_on: Sequence[str] | None,\n suffix: str,\n ) -> Self:\n try:\n return super().join(\n other=other, how=how, left_on=left_on, right_on=right_on, suffix=suffix\n )\n except Exception as e: # noqa: BLE001\n raise catch_polars_exception(e, self._backend_version) from None\n\n\nclass PolarsLazyFrame(PolarsBaseFrame[pl.LazyFrame]):\n # CompliantLazyFrame\n _evaluate_expr: Any\n _evaluate_window_expr: Any\n _evaluate_aliases: Any\n\n @staticmethod\n def _is_native(obj: pl.LazyFrame | Any) -> TypeIs[pl.LazyFrame]:\n return isinstance(obj, pl.LazyFrame)\n\n def to_narwhals(self) -> LazyFrame[pl.LazyFrame]:\n return self._version.lazyframe(self, level="lazy")\n\n def __repr__(self) -> str: # pragma: no cover\n return "PolarsLazyFrame"\n\n def __narwhals_lazyframe__(self) -> Self:\n return self\n\n def __getattr__(self, attr: str) -> Any:\n if attr not in INHERITED_METHODS: # pragma: no cover\n msg = f"{self.__class__.__name__} has not attribute '{attr}'."\n raise AttributeError(msg)\n\n def func(*args: Any, **kwargs: Any) -> Any:\n pos, kwds = extract_args_kwargs(args, kwargs)\n try:\n return self._with_native(getattr(self.native, attr)(*pos, **kwds))\n except pl.exceptions.ColumnNotFoundError as e: # pragma: no cover\n raise ColumnNotFoundError(str(e)) from e\n\n return func\n\n def _iter_columns(self) -> Iterator[PolarsSeries]: # pragma: no cover\n yield from self.collect(self._implementation).iter_columns()\n\n def collect_schema(self) -> dict[str, DType]:\n try:\n return super().collect_schema()\n except Exception as e: # noqa: BLE001\n raise catch_polars_exception(e, self._backend_version) from None\n\n def collect(\n self, backend: Implementation | None, **kwargs: Any\n ) -> CompliantDataFrameAny:\n try:\n result = self.native.collect(**kwargs)\n except Exception as e: # noqa: BLE001\n raise catch_polars_exception(e, self._backend_version) from None\n\n if backend is None or backend is Implementation.POLARS:\n return PolarsDataFrame.from_native(result, context=self)\n\n if backend is Implementation.PANDAS:\n import pandas as pd # ignore-banned-import\n\n from narwhals._pandas_like.dataframe import PandasLikeDataFrame\n\n return PandasLikeDataFrame(\n result.to_pandas(),\n implementation=Implementation.PANDAS,\n backend_version=parse_version(pd),\n version=self._version,\n validate_column_names=False,\n )\n\n if backend is Implementation.PYARROW:\n import pyarrow as pa # ignore-banned-import\n\n from narwhals._arrow.dataframe import ArrowDataFrame\n\n return ArrowDataFrame(\n result.to_arrow(),\n backend_version=parse_version(pa),\n version=self._version,\n validate_column_names=False,\n )\n\n msg = f"Unsupported `backend` value: {backend}" # pragma: no cover\n raise ValueError(msg) # pragma: no cover\n\n def group_by(\n self, keys: Sequence[str] | Sequence[PolarsExpr], *, drop_null_keys: bool\n ) -> PolarsLazyGroupBy:\n from narwhals._polars.group_by import PolarsLazyGroupBy\n\n return PolarsLazyGroupBy(self, keys, drop_null_keys=drop_null_keys)\n\n def drop(self, columns: Sequence[str], *, strict: bool) -> Self:\n if self._backend_version < (1, 0, 0):\n return self._with_native(self.native.drop(columns))\n return self._with_native(self.native.drop(columns, strict=strict))\n | .venv\Lib\site-packages\narwhals\_polars\dataframe.py | dataframe.py | Python | 22,293 | 0.95 | 0.164341 | 0.027372 | awesome-app | 957 | 2025-04-29T11:39:19.858917 | Apache-2.0 | false | fa6538a8bcadf5cfcd7feb3e936efe97 |
from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Any, Callable, Literal\n\nimport polars as pl\n\nfrom narwhals._duration import parse_interval_string\nfrom narwhals._polars.utils import (\n extract_args_kwargs,\n extract_native,\n narwhals_to_native_dtype,\n)\nfrom narwhals._utils import Implementation, requires\n\nif TYPE_CHECKING:\n from collections.abc import Mapping, Sequence\n\n from typing_extensions import Self\n\n from narwhals._expression_parsing import ExprKind, ExprMetadata\n from narwhals._polars.dataframe import Method\n from narwhals._polars.namespace import PolarsNamespace\n from narwhals._utils import Version\n from narwhals.typing import IntoDType\n\n\nclass PolarsExpr:\n def __init__(\n self, expr: pl.Expr, version: Version, backend_version: tuple[int, ...]\n ) -> None:\n self._native_expr = expr\n self._implementation = Implementation.POLARS\n self._version = version\n self._backend_version = backend_version\n self._metadata: ExprMetadata | None = None\n\n @property\n def native(self) -> pl.Expr:\n return self._native_expr\n\n def __repr__(self) -> str: # pragma: no cover\n return "PolarsExpr"\n\n def _with_native(self, expr: pl.Expr) -> Self:\n return self.__class__(expr, self._version, self._backend_version)\n\n @classmethod\n def _from_series(cls, series: Any) -> Self:\n return cls(series.native, series._version, series._backend_version)\n\n def broadcast(self, kind: Literal[ExprKind.AGGREGATION, ExprKind.LITERAL]) -> Self:\n # Let Polars do its thing.\n return self\n\n def __getattr__(self, attr: str) -> Any:\n def func(*args: Any, **kwargs: Any) -> Any:\n pos, kwds = extract_args_kwargs(args, kwargs)\n return self._with_native(getattr(self.native, attr)(*pos, **kwds))\n\n return func\n\n def _renamed_min_periods(self, min_samples: int, /) -> dict[str, Any]:\n name = "min_periods" if self._backend_version < (1, 21, 0) else "min_samples"\n return {name: min_samples}\n\n def cast(self, dtype: IntoDType) -> Self:\n dtype_pl = narwhals_to_native_dtype(dtype, self._version, self._backend_version)\n return self._with_native(self.native.cast(dtype_pl))\n\n def ewm_mean(\n self,\n *,\n com: float | None,\n span: float | None,\n half_life: float | None,\n alpha: float | None,\n adjust: bool,\n min_samples: int,\n ignore_nulls: bool,\n ) -> Self:\n native = self.native.ewm_mean(\n com=com,\n span=span,\n half_life=half_life,\n alpha=alpha,\n adjust=adjust,\n ignore_nulls=ignore_nulls,\n **self._renamed_min_periods(min_samples),\n )\n if self._backend_version < (1,): # pragma: no cover\n native = pl.when(~self.native.is_null()).then(native).otherwise(None)\n return self._with_native(native)\n\n def is_nan(self) -> Self:\n if self._backend_version >= (1, 18):\n native = self.native.is_nan()\n else: # pragma: no cover\n native = pl.when(self.native.is_not_null()).then(self.native.is_nan())\n return self._with_native(native)\n\n def over(self, partition_by: Sequence[str], order_by: Sequence[str]) -> Self:\n if self._backend_version < (1, 9):\n if order_by:\n msg = "`order_by` in Polars requires version 1.10 or greater"\n raise NotImplementedError(msg)\n native = self.native.over(partition_by or pl.lit(1))\n else:\n native = self.native.over(\n partition_by or pl.lit(1), order_by=order_by or None\n )\n return self._with_native(native)\n\n @requires.backend_version((1,))\n def rolling_var(\n self, window_size: int, *, min_samples: int, center: bool, ddof: int\n ) -> Self:\n kwds = self._renamed_min_periods(min_samples)\n native = self.native.rolling_var(\n window_size=window_size, center=center, ddof=ddof, **kwds\n )\n return self._with_native(native)\n\n @requires.backend_version((1,))\n def rolling_std(\n self, window_size: int, *, min_samples: int, center: bool, ddof: int\n ) -> Self:\n kwds = self._renamed_min_periods(min_samples)\n native = self.native.rolling_std(\n window_size=window_size, center=center, ddof=ddof, **kwds\n )\n return self._with_native(native)\n\n def rolling_sum(self, window_size: int, *, min_samples: int, center: bool) -> Self:\n kwds = self._renamed_min_periods(min_samples)\n native = self.native.rolling_sum(window_size=window_size, center=center, **kwds)\n return self._with_native(native)\n\n def rolling_mean(self, window_size: int, *, min_samples: int, center: bool) -> Self:\n kwds = self._renamed_min_periods(min_samples)\n native = self.native.rolling_mean(window_size=window_size, center=center, **kwds)\n return self._with_native(native)\n\n def map_batches(\n self, function: Callable[[Any], Any], return_dtype: IntoDType | None\n ) -> Self:\n return_dtype_pl = (\n narwhals_to_native_dtype(return_dtype, self._version, self._backend_version)\n if return_dtype\n else None\n )\n native = self.native.map_batches(function, return_dtype_pl)\n return self._with_native(native)\n\n @requires.backend_version((1,))\n def replace_strict(\n self,\n old: Sequence[Any] | Mapping[Any, Any],\n new: Sequence[Any],\n *,\n return_dtype: IntoDType | None,\n ) -> Self:\n return_dtype_pl = (\n narwhals_to_native_dtype(return_dtype, self._version, self._backend_version)\n if return_dtype\n else None\n )\n native = self.native.replace_strict(old, new, return_dtype=return_dtype_pl)\n return self._with_native(native)\n\n def __eq__(self, other: object) -> Self: # type: ignore[override]\n return self._with_native(self.native.__eq__(extract_native(other))) # type: ignore[operator]\n\n def __ne__(self, other: object) -> Self: # type: ignore[override]\n return self._with_native(self.native.__ne__(extract_native(other))) # type: ignore[operator]\n\n def __ge__(self, other: Any) -> Self:\n return self._with_native(self.native.__ge__(extract_native(other)))\n\n def __gt__(self, other: Any) -> Self:\n return self._with_native(self.native.__gt__(extract_native(other)))\n\n def __le__(self, other: Any) -> Self:\n return self._with_native(self.native.__le__(extract_native(other)))\n\n def __lt__(self, other: Any) -> Self:\n return self._with_native(self.native.__lt__(extract_native(other)))\n\n def __and__(self, other: PolarsExpr | bool | Any) -> Self:\n return self._with_native(self.native.__and__(extract_native(other))) # type: ignore[operator]\n\n def __or__(self, other: PolarsExpr | bool | Any) -> Self:\n return self._with_native(self.native.__or__(extract_native(other))) # type: ignore[operator]\n\n def __add__(self, other: Any) -> Self:\n return self._with_native(self.native.__add__(extract_native(other)))\n\n def __sub__(self, other: Any) -> Self:\n return self._with_native(self.native.__sub__(extract_native(other)))\n\n def __mul__(self, other: Any) -> Self:\n return self._with_native(self.native.__mul__(extract_native(other)))\n\n def __pow__(self, other: Any) -> Self:\n return self._with_native(self.native.__pow__(extract_native(other)))\n\n def __truediv__(self, other: Any) -> Self:\n return self._with_native(self.native.__truediv__(extract_native(other)))\n\n def __floordiv__(self, other: Any) -> Self:\n return self._with_native(self.native.__floordiv__(extract_native(other)))\n\n def __mod__(self, other: Any) -> Self:\n return self._with_native(self.native.__mod__(extract_native(other)))\n\n def __invert__(self) -> Self:\n return self._with_native(self.native.__invert__())\n\n def cum_count(self, *, reverse: bool) -> Self:\n return self._with_native(self.native.cum_count(reverse=reverse))\n\n def __narwhals_expr__(self) -> None: ...\n def __narwhals_namespace__(self) -> PolarsNamespace: # pragma: no cover\n from narwhals._polars.namespace import PolarsNamespace\n\n return PolarsNamespace(\n backend_version=self._backend_version, version=self._version\n )\n\n @property\n def dt(self) -> PolarsExprDateTimeNamespace:\n return PolarsExprDateTimeNamespace(self)\n\n @property\n def str(self) -> PolarsExprStringNamespace:\n return PolarsExprStringNamespace(self)\n\n @property\n def cat(self) -> PolarsExprCatNamespace:\n return PolarsExprCatNamespace(self)\n\n @property\n def name(self) -> PolarsExprNameNamespace:\n return PolarsExprNameNamespace(self)\n\n @property\n def list(self) -> PolarsExprListNamespace:\n return PolarsExprListNamespace(self)\n\n @property\n def struct(self) -> PolarsExprStructNamespace:\n return PolarsExprStructNamespace(self)\n\n # CompliantExpr\n _alias_output_names: Any\n _evaluate_aliases: Any\n _evaluate_output_names: Any\n _is_multi_output_unnamed: Any\n __call__: Any\n from_column_names: Any\n from_column_indices: Any\n _eval_names_indices: Any\n\n # Polars\n abs: Method[Self]\n all: Method[Self]\n any: Method[Self]\n alias: Method[Self]\n arg_max: Method[Self]\n arg_min: Method[Self]\n arg_true: Method[Self]\n clip: Method[Self]\n count: Method[Self]\n cum_max: Method[Self]\n cum_min: Method[Self]\n cum_prod: Method[Self]\n cum_sum: Method[Self]\n diff: Method[Self]\n drop_nulls: Method[Self]\n exp: Method[Self]\n fill_null: Method[Self]\n gather_every: Method[Self]\n head: Method[Self]\n is_finite: Method[Self]\n is_first_distinct: Method[Self]\n is_in: Method[Self]\n is_last_distinct: Method[Self]\n is_null: Method[Self]\n is_unique: Method[Self]\n kurtosis: Method[Self]\n len: Method[Self]\n log: Method[Self]\n max: Method[Self]\n mean: Method[Self]\n median: Method[Self]\n min: Method[Self]\n mode: Method[Self]\n n_unique: Method[Self]\n null_count: Method[Self]\n quantile: Method[Self]\n rank: Method[Self]\n round: Method[Self]\n sample: Method[Self]\n shift: Method[Self]\n skew: Method[Self]\n sqrt: Method[Self]\n std: Method[Self]\n sum: Method[Self]\n sort: Method[Self]\n tail: Method[Self]\n unique: Method[Self]\n var: Method[Self]\n\n\nclass PolarsExprNamespace:\n def __init__(self, expr: PolarsExpr) -> None:\n self._expr = expr\n\n @property\n def compliant(self) -> PolarsExpr:\n return self._expr\n\n @property\n def native(self) -> pl.Expr:\n return self._expr.native\n\n\nclass PolarsExprDateTimeNamespace(PolarsExprNamespace):\n def truncate(self, every: str) -> PolarsExpr:\n parse_interval_string(every) # Ensure consistent error message is raised.\n return self.compliant._with_native(self.native.dt.truncate(every))\n\n def __getattr__(self, attr: str) -> Callable[[Any], PolarsExpr]:\n def func(*args: Any, **kwargs: Any) -> PolarsExpr:\n pos, kwds = extract_args_kwargs(args, kwargs)\n return self.compliant._with_native(\n getattr(self.native.dt, attr)(*pos, **kwds)\n )\n\n return func\n\n to_string: Method[PolarsExpr]\n replace_time_zone: Method[PolarsExpr]\n convert_time_zone: Method[PolarsExpr]\n timestamp: Method[PolarsExpr]\n date: Method[PolarsExpr]\n year: Method[PolarsExpr]\n month: Method[PolarsExpr]\n day: Method[PolarsExpr]\n hour: Method[PolarsExpr]\n minute: Method[PolarsExpr]\n second: Method[PolarsExpr]\n millisecond: Method[PolarsExpr]\n microsecond: Method[PolarsExpr]\n nanosecond: Method[PolarsExpr]\n ordinal_day: Method[PolarsExpr]\n weekday: Method[PolarsExpr]\n total_minutes: Method[PolarsExpr]\n total_seconds: Method[PolarsExpr]\n total_milliseconds: Method[PolarsExpr]\n total_microseconds: Method[PolarsExpr]\n total_nanoseconds: Method[PolarsExpr]\n\n\nclass PolarsExprStringNamespace(PolarsExprNamespace):\n def zfill(self, width: int) -> PolarsExpr:\n backend_version = self.compliant._backend_version\n native_result = self.native.str.zfill(width)\n\n if backend_version < (0, 20, 5): # pragma: no cover\n # Reason:\n # `TypeError: argument 'length': 'Expr' object cannot be interpreted as an integer`\n # in `native_expr.str.slice(1, length)`\n msg = "`zfill` is only available in 'polars>=0.20.5', found version '0.20.4'."\n raise NotImplementedError(msg)\n\n if backend_version <= (1, 30, 0):\n length = self.native.str.len_chars()\n less_than_width = length < width\n plus = "+"\n starts_with_plus = self.native.str.starts_with(plus)\n native_result = (\n pl.when(starts_with_plus & less_than_width)\n .then(\n self.native.str.slice(1, length)\n .str.zfill(width - 1)\n .str.pad_start(width, plus)\n )\n .otherwise(native_result)\n )\n\n return self.compliant._with_native(native_result)\n\n def __getattr__(self, attr: str) -> Callable[[Any], PolarsExpr]:\n def func(*args: Any, **kwargs: Any) -> PolarsExpr:\n pos, kwds = extract_args_kwargs(args, kwargs)\n return self.compliant._with_native(\n getattr(self.native.str, attr)(*pos, **kwds)\n )\n\n return func\n\n len_chars: Method[PolarsExpr]\n replace: Method[PolarsExpr]\n replace_all: Method[PolarsExpr]\n strip_chars: Method[PolarsExpr]\n starts_with: Method[PolarsExpr]\n ends_with: Method[PolarsExpr]\n contains: Method[PolarsExpr]\n slice: Method[PolarsExpr]\n split: Method[PolarsExpr]\n to_date: Method[PolarsExpr]\n to_datetime: Method[PolarsExpr]\n to_lowercase: Method[PolarsExpr]\n to_uppercase: Method[PolarsExpr]\n\n\nclass PolarsExprCatNamespace(PolarsExprNamespace):\n def __getattr__(self, attr: str) -> Callable[[Any], PolarsExpr]:\n def func(*args: Any, **kwargs: Any) -> PolarsExpr:\n pos, kwds = extract_args_kwargs(args, kwargs)\n return self.compliant._with_native(\n getattr(self.native.cat, attr)(*pos, **kwds)\n )\n\n return func\n\n get_categories: Method[PolarsExpr]\n\n\nclass PolarsExprNameNamespace(PolarsExprNamespace):\n def __getattr__(self, attr: str) -> Callable[[Any], PolarsExpr]:\n def func(*args: Any, **kwargs: Any) -> PolarsExpr:\n pos, kwds = extract_args_kwargs(args, kwargs)\n return self.compliant._with_native(\n getattr(self.native.name, attr)(*pos, **kwds)\n )\n\n return func\n\n keep: Method[PolarsExpr]\n map: Method[PolarsExpr]\n prefix: Method[PolarsExpr]\n suffix: Method[PolarsExpr]\n to_lowercase: Method[PolarsExpr]\n to_uppercase: Method[PolarsExpr]\n\n\nclass PolarsExprListNamespace(PolarsExprNamespace):\n def len(self) -> PolarsExpr:\n native_expr = self.compliant._native_expr\n native_result = native_expr.list.len()\n\n if self.compliant._backend_version < (1, 16): # pragma: no cover\n native_result = (\n pl.when(~native_expr.is_null()).then(native_result).cast(pl.UInt32())\n )\n elif self.compliant._backend_version < (1, 17): # pragma: no cover\n native_result = native_result.cast(pl.UInt32())\n\n return self.compliant._with_native(native_result)\n\n # TODO(FBruzzesi): Remove `pragma: no cover` once other namespace methods are added\n def __getattr__(self, attr: str) -> Callable[[Any], PolarsExpr]: # pragma: no cover\n def func(*args: Any, **kwargs: Any) -> PolarsExpr:\n pos, kwds = extract_args_kwargs(args, kwargs)\n return self.compliant._with_native(\n getattr(self.native.list, attr)(*pos, **kwds)\n )\n\n return func\n\n\nclass PolarsExprStructNamespace(PolarsExprNamespace):\n def __getattr__(self, attr: str) -> Callable[[Any], PolarsExpr]: # pragma: no cover\n def func(*args: Any, **kwargs: Any) -> PolarsExpr:\n pos, kwds = extract_args_kwargs(args, kwargs)\n return self.compliant._with_native(\n getattr(self.native.struct, attr)(*pos, **kwds)\n )\n\n return func\n\n field: Method[PolarsExpr]\n | .venv\Lib\site-packages\narwhals\_polars\expr.py | expr.py | Python | 16,673 | 0.95 | 0.171843 | 0.025316 | node-utils | 986 | 2025-06-10T21:51:24.253907 | MIT | false | 47080ec50d16254201d6ec55696c7b28 |
from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, cast\n\nfrom narwhals._utils import is_sequence_of\n\nif TYPE_CHECKING:\n from collections.abc import Iterator, Sequence\n\n from polars.dataframe.group_by import GroupBy as NativeGroupBy\n from polars.lazyframe.group_by import LazyGroupBy as NativeLazyGroupBy\n\n from narwhals._polars.dataframe import PolarsDataFrame, PolarsLazyFrame\n from narwhals._polars.expr import PolarsExpr\n\n\nclass PolarsGroupBy:\n _compliant_frame: PolarsDataFrame\n _grouped: NativeGroupBy\n _drop_null_keys: bool\n _output_names: Sequence[str]\n\n @property\n def compliant(self) -> PolarsDataFrame:\n return self._compliant_frame\n\n def __init__(\n self,\n df: PolarsDataFrame,\n keys: Sequence[PolarsExpr] | Sequence[str],\n /,\n *,\n drop_null_keys: bool,\n ) -> None:\n self._keys = list(keys)\n self._compliant_frame = df.drop_nulls(keys) if drop_null_keys else df\n self._grouped = (\n self.compliant.native.group_by(keys)\n if is_sequence_of(keys, str)\n else self.compliant.native.group_by(arg.native for arg in keys)\n )\n\n def agg(self, *aggs: PolarsExpr) -> PolarsDataFrame:\n agg_result = self._grouped.agg(arg.native for arg in aggs)\n return self.compliant._with_native(agg_result)\n\n def __iter__(self) -> Iterator[tuple[tuple[str, ...], PolarsDataFrame]]:\n for key, df in self._grouped:\n yield tuple(cast("str", key)), self.compliant._with_native(df)\n\n\nclass PolarsLazyGroupBy:\n _compliant_frame: PolarsLazyFrame\n _grouped: NativeLazyGroupBy\n _drop_null_keys: bool\n _output_names: Sequence[str]\n\n @property\n def compliant(self) -> PolarsLazyFrame:\n return self._compliant_frame\n\n def __init__(\n self,\n df: PolarsLazyFrame,\n keys: Sequence[PolarsExpr] | Sequence[str],\n /,\n *,\n drop_null_keys: bool,\n ) -> None:\n self._keys = list(keys)\n self._compliant_frame = df.drop_nulls(keys) if drop_null_keys else df\n self._grouped = (\n self.compliant.native.group_by(keys)\n if is_sequence_of(keys, str)\n else self.compliant.native.group_by(arg.native for arg in keys)\n )\n\n def agg(self, *aggs: PolarsExpr) -> PolarsLazyFrame:\n agg_result = self._grouped.agg(arg.native for arg in aggs)\n return self.compliant._with_native(agg_result)\n | .venv\Lib\site-packages\narwhals\_polars\group_by.py | group_by.py | Python | 2,491 | 0.85 | 0.2375 | 0.03125 | vue-tools | 503 | 2023-09-19T13:42:24.047320 | BSD-3-Clause | false | 55dcc6afa69b74964068fab5714f564d |
from __future__ import annotations\n\nimport operator\nfrom typing import TYPE_CHECKING, Any, Literal, cast, overload\n\nimport polars as pl\n\nfrom narwhals._polars.expr import PolarsExpr\nfrom narwhals._polars.series import PolarsSeries\nfrom narwhals._polars.utils import extract_args_kwargs, narwhals_to_native_dtype\nfrom narwhals._utils import Implementation, requires\nfrom narwhals.dependencies import is_numpy_array_2d\nfrom narwhals.dtypes import DType\n\nif TYPE_CHECKING:\n from collections.abc import Iterable, Mapping, Sequence\n from datetime import timezone\n\n from narwhals._compliant import CompliantSelectorNamespace, CompliantWhen\n from narwhals._polars.dataframe import Method, PolarsDataFrame, PolarsLazyFrame\n from narwhals._polars.typing import FrameT\n from narwhals._utils import Version, _FullContext\n from narwhals.schema import Schema\n from narwhals.typing import Into1DArray, IntoDType, TimeUnit, _2DArray\n\n\nclass PolarsNamespace:\n all: Method[PolarsExpr]\n col: Method[PolarsExpr]\n exclude: Method[PolarsExpr]\n sum_horizontal: Method[PolarsExpr]\n min_horizontal: Method[PolarsExpr]\n max_horizontal: Method[PolarsExpr]\n\n # NOTE: `pyright` accepts, `mypy` doesn't highlight the issue\n # error: Type argument "PolarsExpr" of "CompliantWhen" must be a subtype of "CompliantExpr[Any, Any]"\n when: Method[CompliantWhen[PolarsDataFrame, PolarsSeries, PolarsExpr]] # type: ignore[type-var]\n\n def __init__(self, *, backend_version: tuple[int, ...], version: Version) -> None:\n self._backend_version = backend_version\n self._implementation = Implementation.POLARS\n self._version = version\n\n def __getattr__(self, attr: str) -> Any:\n def func(*args: Any, **kwargs: Any) -> Any:\n pos, kwds = extract_args_kwargs(args, kwargs)\n return self._expr(\n getattr(pl, attr)(*pos, **kwds),\n version=self._version,\n backend_version=self._backend_version,\n )\n\n return func\n\n @property\n def _dataframe(self) -> type[PolarsDataFrame]:\n from narwhals._polars.dataframe import PolarsDataFrame\n\n return PolarsDataFrame\n\n @property\n def _lazyframe(self) -> type[PolarsLazyFrame]:\n from narwhals._polars.dataframe import PolarsLazyFrame\n\n return PolarsLazyFrame\n\n @property\n def _expr(self) -> type[PolarsExpr]:\n return PolarsExpr\n\n @property\n def _series(self) -> type[PolarsSeries]:\n return PolarsSeries\n\n @overload\n def from_native(self, data: pl.DataFrame, /) -> PolarsDataFrame: ...\n @overload\n def from_native(self, data: pl.LazyFrame, /) -> PolarsLazyFrame: ...\n @overload\n def from_native(self, data: pl.Series, /) -> PolarsSeries: ...\n def from_native(\n self, data: pl.DataFrame | pl.LazyFrame | pl.Series | Any, /\n ) -> PolarsDataFrame | PolarsLazyFrame | PolarsSeries:\n if self._dataframe._is_native(data):\n return self._dataframe.from_native(data, context=self)\n elif self._series._is_native(data):\n return self._series.from_native(data, context=self)\n elif self._lazyframe._is_native(data):\n return self._lazyframe.from_native(data, context=self)\n else: # pragma: no cover\n msg = f"Unsupported type: {type(data).__name__!r}"\n raise TypeError(msg)\n\n @overload\n def from_numpy(self, data: Into1DArray, /, schema: None = ...) -> PolarsSeries: ...\n\n @overload\n def from_numpy(\n self,\n data: _2DArray,\n /,\n schema: Mapping[str, DType] | Schema | Sequence[str] | None,\n ) -> PolarsDataFrame: ...\n\n def from_numpy(\n self,\n data: Into1DArray | _2DArray,\n /,\n schema: Mapping[str, DType] | Schema | Sequence[str] | None = None,\n ) -> PolarsDataFrame | PolarsSeries:\n if is_numpy_array_2d(data):\n return self._dataframe.from_numpy(data, schema=schema, context=self)\n return self._series.from_numpy(data, context=self) # pragma: no cover\n\n @requires.backend_version(\n (1, 0, 0), "Please use `col` for columns selection instead."\n )\n def nth(self, *indices: int) -> PolarsExpr:\n return self._expr(\n pl.nth(*indices), version=self._version, backend_version=self._backend_version\n )\n\n def len(self) -> PolarsExpr:\n if self._backend_version < (0, 20, 5):\n return self._expr(\n pl.count().alias("len"), self._version, self._backend_version\n )\n return self._expr(pl.len(), self._version, self._backend_version)\n\n def all_horizontal(self, *exprs: PolarsExpr, ignore_nulls: bool) -> PolarsExpr:\n it = (expr.fill_null(True) for expr in exprs) if ignore_nulls else iter(exprs) # noqa: FBT003\n return self._expr(\n pl.all_horizontal(*(expr.native for expr in it)),\n self._version,\n self._backend_version,\n )\n\n def any_horizontal(self, *exprs: PolarsExpr, ignore_nulls: bool) -> PolarsExpr:\n it = (expr.fill_null(False) for expr in exprs) if ignore_nulls else iter(exprs) # noqa: FBT003\n return self._expr(\n pl.any_horizontal(*(expr.native for expr in it)),\n self._version,\n self._backend_version,\n )\n\n def concat(\n self,\n items: Iterable[FrameT],\n *,\n how: Literal["vertical", "horizontal", "diagonal"],\n ) -> PolarsDataFrame | PolarsLazyFrame:\n result = pl.concat((item.native for item in items), how=how)\n if isinstance(result, pl.DataFrame):\n return self._dataframe(\n result, backend_version=self._backend_version, version=self._version\n )\n return self._lazyframe.from_native(result, context=self)\n\n def lit(self, value: Any, dtype: IntoDType | None) -> PolarsExpr:\n if dtype is not None:\n return self._expr(\n pl.lit(\n value,\n dtype=narwhals_to_native_dtype(\n dtype, self._version, self._backend_version\n ),\n ),\n version=self._version,\n backend_version=self._backend_version,\n )\n return self._expr(\n pl.lit(value), version=self._version, backend_version=self._backend_version\n )\n\n def mean_horizontal(self, *exprs: PolarsExpr) -> PolarsExpr:\n if self._backend_version < (0, 20, 8):\n return self._expr(\n pl.sum_horizontal(e._native_expr for e in exprs)\n / pl.sum_horizontal(1 - e.is_null()._native_expr for e in exprs),\n version=self._version,\n backend_version=self._backend_version,\n )\n\n return self._expr(\n pl.mean_horizontal(e._native_expr for e in exprs),\n version=self._version,\n backend_version=self._backend_version,\n )\n\n def concat_str(\n self, *exprs: PolarsExpr, separator: str, ignore_nulls: bool\n ) -> PolarsExpr:\n pl_exprs: list[pl.Expr] = [expr._native_expr for expr in exprs]\n\n if self._backend_version < (0, 20, 6):\n null_mask = [expr.is_null() for expr in pl_exprs]\n sep = pl.lit(separator)\n\n if not ignore_nulls:\n null_mask_result = pl.any_horizontal(*null_mask)\n output_expr = pl.reduce(\n lambda x, y: x.cast(pl.String()) + sep + y.cast(pl.String()), # type: ignore[arg-type,return-value]\n pl_exprs,\n )\n result = pl.when(~null_mask_result).then(output_expr)\n else:\n init_value, *values = [\n pl.when(nm).then(pl.lit("")).otherwise(expr.cast(pl.String()))\n for expr, nm in zip(pl_exprs, null_mask)\n ]\n separators = [\n pl.when(~nm).then(sep).otherwise(pl.lit("")) for nm in null_mask[:-1]\n ]\n\n result = pl.fold( # type: ignore[assignment]\n acc=init_value,\n function=operator.add,\n exprs=[s + v for s, v in zip(separators, values)],\n )\n\n return self._expr(\n result, version=self._version, backend_version=self._backend_version\n )\n\n return self._expr(\n pl.concat_str(pl_exprs, separator=separator, ignore_nulls=ignore_nulls),\n version=self._version,\n backend_version=self._backend_version,\n )\n\n # NOTE: Implementation is too different to annotate correctly (vs other `*SelectorNamespace`)\n # 1. Others have lots of private stuff for code reuse\n # i. None of that is useful here\n # 2. We don't have a `PolarsSelector` abstraction, and just use `PolarsExpr`\n @property\n def selectors(self) -> CompliantSelectorNamespace[PolarsDataFrame, PolarsSeries]:\n return cast(\n "CompliantSelectorNamespace[PolarsDataFrame, PolarsSeries]",\n PolarsSelectorNamespace(self),\n )\n\n\nclass PolarsSelectorNamespace:\n def __init__(self, context: _FullContext, /) -> None:\n self._implementation = context._implementation\n self._backend_version = context._backend_version\n self._version = context._version\n\n def by_dtype(self, dtypes: Iterable[DType]) -> PolarsExpr:\n native_dtypes = [\n narwhals_to_native_dtype(\n dtype, self._version, self._backend_version\n ).__class__\n if isinstance(dtype, type) and issubclass(dtype, DType)\n else narwhals_to_native_dtype(dtype, self._version, self._backend_version)\n for dtype in dtypes\n ]\n return PolarsExpr(\n pl.selectors.by_dtype(native_dtypes),\n version=self._version,\n backend_version=self._backend_version,\n )\n\n def matches(self, pattern: str) -> PolarsExpr:\n return PolarsExpr(\n pl.selectors.matches(pattern=pattern),\n version=self._version,\n backend_version=self._backend_version,\n )\n\n def numeric(self) -> PolarsExpr:\n return PolarsExpr(\n pl.selectors.numeric(),\n version=self._version,\n backend_version=self._backend_version,\n )\n\n def boolean(self) -> PolarsExpr:\n return PolarsExpr(\n pl.selectors.boolean(),\n version=self._version,\n backend_version=self._backend_version,\n )\n\n def string(self) -> PolarsExpr:\n return PolarsExpr(\n pl.selectors.string(),\n version=self._version,\n backend_version=self._backend_version,\n )\n\n def categorical(self) -> PolarsExpr:\n return PolarsExpr(\n pl.selectors.categorical(),\n version=self._version,\n backend_version=self._backend_version,\n )\n\n def all(self) -> PolarsExpr:\n return PolarsExpr(\n pl.selectors.all(),\n version=self._version,\n backend_version=self._backend_version,\n )\n\n def datetime(\n self,\n time_unit: TimeUnit | Iterable[TimeUnit] | None,\n time_zone: str | timezone | Iterable[str | timezone | None] | None,\n ) -> PolarsExpr:\n return PolarsExpr(\n pl.selectors.datetime(time_unit=time_unit, time_zone=time_zone), # type: ignore[arg-type]\n version=self._version,\n backend_version=self._backend_version,\n )\n | .venv\Lib\site-packages\narwhals\_polars\namespace.py | namespace.py | Python | 11,606 | 0.95 | 0.2 | 0.026022 | node-utils | 678 | 2024-10-01T21:01:38.045017 | MIT | false | 3bb8a88ba7050b21de3f1e891d1dd128 |
from __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Any, cast, overload\n\nimport polars as pl\n\nfrom narwhals._polars.utils import (\n catch_polars_exception,\n extract_args_kwargs,\n extract_native,\n narwhals_to_native_dtype,\n native_to_narwhals_dtype,\n)\nfrom narwhals._utils import Implementation, requires, validate_backend_version\nfrom narwhals.dependencies import is_numpy_array_1d\n\nif TYPE_CHECKING:\n from collections.abc import Iterable, Iterator, Mapping, Sequence\n from types import ModuleType\n from typing import TypeVar\n\n import pandas as pd\n import pyarrow as pa\n from typing_extensions import Self, TypeIs\n\n from narwhals._polars.dataframe import Method, PolarsDataFrame\n from narwhals._polars.expr import PolarsExpr\n from narwhals._polars.namespace import PolarsNamespace\n from narwhals._utils import Version, _FullContext\n from narwhals.dtypes import DType\n from narwhals.series import Series\n from narwhals.typing import Into1DArray, IntoDType, MultiIndexSelector, _1DArray\n\n T = TypeVar("T")\n\n\n# Series methods where PolarsSeries just defers to Polars.Series directly.\nINHERITED_METHODS = frozenset(\n [\n "__add__",\n "__and__",\n "__floordiv__",\n "__invert__",\n "__iter__",\n "__mod__",\n "__mul__",\n "__or__",\n "__pow__",\n "__radd__",\n "__rand__",\n "__rfloordiv__",\n "__rmod__",\n "__rmul__",\n "__ror__",\n "__rsub__",\n "__rtruediv__",\n "__sub__",\n "__truediv__",\n "abs",\n "all",\n "any",\n "arg_max",\n "arg_min",\n "arg_true",\n "clip",\n "count",\n "cum_max",\n "cum_min",\n "cum_prod",\n "cum_sum",\n "diff",\n "drop_nulls",\n "exp",\n "fill_null",\n "filter",\n "gather_every",\n "head",\n "is_between",\n "is_finite",\n "is_first_distinct",\n "is_in",\n "is_last_distinct",\n "is_null",\n "is_sorted",\n "is_unique",\n "item",\n "kurtosis",\n "len",\n "log",\n "max",\n "mean",\n "min",\n "mode",\n "n_unique",\n "null_count",\n "quantile",\n "rank",\n "round",\n "sample",\n "shift",\n "skew",\n "sqrt",\n "std",\n "sum",\n "tail",\n "to_arrow",\n "to_frame",\n "to_list",\n "to_pandas",\n "unique",\n "var",\n "zip_with",\n ]\n)\n\n\nclass PolarsSeries:\n def __init__(\n self, series: pl.Series, *, backend_version: tuple[int, ...], version: Version\n ) -> None:\n self._native_series: pl.Series = series\n self._backend_version = backend_version\n self._implementation = Implementation.POLARS\n self._version = version\n validate_backend_version(self._implementation, self._backend_version)\n\n def __repr__(self) -> str: # pragma: no cover\n return "PolarsSeries"\n\n def __narwhals_namespace__(self) -> PolarsNamespace:\n from narwhals._polars.namespace import PolarsNamespace\n\n return PolarsNamespace(\n backend_version=self._backend_version, version=self._version\n )\n\n def __narwhals_series__(self) -> Self:\n return self\n\n def __native_namespace__(self) -> ModuleType:\n if self._implementation is Implementation.POLARS:\n return self._implementation.to_native_namespace()\n\n msg = f"Expected polars, got: {type(self._implementation)}" # pragma: no cover\n raise AssertionError(msg)\n\n def _with_version(self, version: Version) -> Self:\n return self.__class__(\n self.native, backend_version=self._backend_version, version=version\n )\n\n @classmethod\n def from_iterable(\n cls,\n data: Iterable[Any],\n *,\n context: _FullContext,\n name: str = "",\n dtype: IntoDType | None = None,\n ) -> Self:\n version = context._version\n backend_version = context._backend_version\n dtype_pl = (\n narwhals_to_native_dtype(dtype, version, backend_version) if dtype else None\n )\n # NOTE: `Iterable` is fine, annotation is overly narrow\n # https://github.com/pola-rs/polars/blob/82d57a4ee41f87c11ca1b1af15488459727efdd7/py-polars/polars/series/series.py#L332-L333\n native = pl.Series(name=name, values=cast("Sequence[Any]", data), dtype=dtype_pl)\n return cls.from_native(native, context=context)\n\n @staticmethod\n def _is_native(obj: pl.Series | Any) -> TypeIs[pl.Series]:\n return isinstance(obj, pl.Series)\n\n @classmethod\n def from_native(cls, data: pl.Series, /, *, context: _FullContext) -> Self:\n return cls(\n data, backend_version=context._backend_version, version=context._version\n )\n\n @classmethod\n def from_numpy(cls, data: Into1DArray, /, *, context: _FullContext) -> Self:\n native = pl.Series(data if is_numpy_array_1d(data) else [data])\n return cls.from_native(native, context=context)\n\n def to_narwhals(self) -> Series[pl.Series]:\n return self._version.series(self, level="full")\n\n def _with_native(self, series: pl.Series) -> Self:\n return self.__class__(\n series, backend_version=self._backend_version, version=self._version\n )\n\n @overload\n def _from_native_object(self, series: pl.Series) -> Self: ...\n\n @overload\n def _from_native_object(self, series: pl.DataFrame) -> PolarsDataFrame: ...\n\n @overload\n def _from_native_object(self, series: T) -> T: ...\n\n def _from_native_object(\n self, series: pl.Series | pl.DataFrame | T\n ) -> Self | PolarsDataFrame | T:\n if self._is_native(series):\n return self._with_native(series)\n if isinstance(series, pl.DataFrame):\n from narwhals._polars.dataframe import PolarsDataFrame\n\n return PolarsDataFrame.from_native(series, context=self)\n # scalar\n return series\n\n def _to_expr(self) -> PolarsExpr:\n return self.__narwhals_namespace__()._expr._from_series(self)\n\n def __getattr__(self, attr: str) -> Any:\n if attr not in INHERITED_METHODS:\n msg = f"{self.__class__.__name__} has not attribute '{attr}'."\n raise AttributeError(msg)\n\n def func(*args: Any, **kwargs: Any) -> Any:\n pos, kwds = extract_args_kwargs(args, kwargs)\n return self._from_native_object(getattr(self.native, attr)(*pos, **kwds))\n\n return func\n\n def __len__(self) -> int:\n return len(self.native)\n\n @property\n def name(self) -> str:\n return self.native.name\n\n @property\n def dtype(self) -> DType:\n return native_to_narwhals_dtype(\n self.native.dtype, self._version, self._backend_version\n )\n\n @property\n def native(self) -> pl.Series:\n return self._native_series\n\n def alias(self, name: str) -> Self:\n return self._from_native_object(self.native.alias(name))\n\n def __getitem__(self, item: MultiIndexSelector[Self]) -> Any | Self:\n if isinstance(item, PolarsSeries):\n return self._from_native_object(self.native.__getitem__(item.native))\n return self._from_native_object(self.native.__getitem__(item))\n\n def cast(self, dtype: IntoDType) -> Self:\n dtype_pl = narwhals_to_native_dtype(dtype, self._version, self._backend_version)\n return self._with_native(self.native.cast(dtype_pl))\n\n @requires.backend_version((1,))\n def replace_strict(\n self,\n old: Sequence[Any] | Mapping[Any, Any],\n new: Sequence[Any],\n *,\n return_dtype: IntoDType | None,\n ) -> Self:\n ser = self.native\n dtype = (\n narwhals_to_native_dtype(return_dtype, self._version, self._backend_version)\n if return_dtype\n else None\n )\n return self._with_native(ser.replace_strict(old, new, return_dtype=dtype))\n\n def to_numpy(self, dtype: Any = None, *, copy: bool | None = None) -> _1DArray:\n return self.__array__(dtype, copy=copy)\n\n def __array__(self, dtype: Any, *, copy: bool | None) -> _1DArray:\n if self._backend_version < (0, 20, 29):\n return self.native.__array__(dtype=dtype)\n return self.native.__array__(dtype=dtype, copy=copy)\n\n def __eq__(self, other: object) -> Self: # type: ignore[override]\n return self._with_native(self.native.__eq__(extract_native(other)))\n\n def __ne__(self, other: object) -> Self: # type: ignore[override]\n return self._with_native(self.native.__ne__(extract_native(other)))\n\n # NOTE: `pyright` is being reasonable here\n def __ge__(self, other: Any) -> Self:\n return self._with_native(self.native.__ge__(extract_native(other))) # pyright: ignore[reportArgumentType]\n\n def __gt__(self, other: Any) -> Self:\n return self._with_native(self.native.__gt__(extract_native(other))) # pyright: ignore[reportArgumentType]\n\n def __le__(self, other: Any) -> Self:\n return self._with_native(self.native.__le__(extract_native(other))) # pyright: ignore[reportArgumentType]\n\n def __lt__(self, other: Any) -> Self:\n return self._with_native(self.native.__lt__(extract_native(other))) # pyright: ignore[reportArgumentType]\n\n def __rpow__(self, other: PolarsSeries | Any) -> Self:\n result = self.native.__rpow__(extract_native(other))\n if self._backend_version < (1, 16, 1):\n # Explicitly set alias to work around https://github.com/pola-rs/polars/issues/20071\n result = result.alias(self.name)\n return self._with_native(result)\n\n def is_nan(self) -> Self:\n try:\n native_is_nan = self.native.is_nan()\n except Exception as e: # noqa: BLE001\n raise catch_polars_exception(e, self._backend_version) from None\n if self._backend_version < (1, 18): # pragma: no cover\n select = pl.when(self.native.is_not_null()).then(native_is_nan)\n return self._with_native(pl.select(select)[self.name])\n return self._with_native(native_is_nan)\n\n def median(self) -> Any:\n from narwhals.exceptions import InvalidOperationError\n\n if not self.dtype.is_numeric():\n msg = "`median` operation not supported for non-numeric input type."\n raise InvalidOperationError(msg)\n\n return self.native.median()\n\n def to_dummies(self, *, separator: str, drop_first: bool) -> PolarsDataFrame:\n from narwhals._polars.dataframe import PolarsDataFrame\n\n if self._backend_version < (0, 20, 15):\n has_nulls = self.native.is_null().any()\n result = self.native.to_dummies(separator=separator)\n output_columns = result.columns\n if drop_first:\n _ = output_columns.pop(int(has_nulls))\n\n result = result.select(output_columns)\n else:\n result = self.native.to_dummies(separator=separator, drop_first=drop_first)\n result = result.with_columns(pl.all().cast(pl.Int8))\n return PolarsDataFrame.from_native(result, context=self)\n\n def ewm_mean(\n self,\n *,\n com: float | None,\n span: float | None,\n half_life: float | None,\n alpha: float | None,\n adjust: bool,\n min_samples: int,\n ignore_nulls: bool,\n ) -> Self:\n extra_kwargs = (\n {"min_periods": min_samples}\n if self._backend_version < (1, 21, 0)\n else {"min_samples": min_samples}\n )\n\n native_result = self.native.ewm_mean(\n com=com,\n span=span,\n half_life=half_life,\n alpha=alpha,\n adjust=adjust,\n ignore_nulls=ignore_nulls,\n **extra_kwargs,\n )\n if self._backend_version < (1,): # pragma: no cover\n return self._with_native(\n pl.select(\n pl.when(~self.native.is_null()).then(native_result).otherwise(None)\n )[self.native.name]\n )\n\n return self._with_native(native_result)\n\n @requires.backend_version((1,))\n def rolling_var(\n self, window_size: int, *, min_samples: int, center: bool, ddof: int\n ) -> Self:\n extra_kwargs: dict[str, Any] = (\n {"min_periods": min_samples}\n if self._backend_version < (1, 21, 0)\n else {"min_samples": min_samples}\n )\n return self._with_native(\n self.native.rolling_var(\n window_size=window_size, center=center, ddof=ddof, **extra_kwargs\n )\n )\n\n @requires.backend_version((1,))\n def rolling_std(\n self, window_size: int, *, min_samples: int, center: bool, ddof: int\n ) -> Self:\n extra_kwargs: dict[str, Any] = (\n {"min_periods": min_samples}\n if self._backend_version < (1, 21, 0)\n else {"min_samples": min_samples}\n )\n return self._with_native(\n self.native.rolling_std(\n window_size=window_size, center=center, ddof=ddof, **extra_kwargs\n )\n )\n\n def rolling_sum(self, window_size: int, *, min_samples: int, center: bool) -> Self:\n extra_kwargs: dict[str, Any] = (\n {"min_periods": min_samples}\n if self._backend_version < (1, 21, 0)\n else {"min_samples": min_samples}\n )\n return self._with_native(\n self.native.rolling_sum(\n window_size=window_size, center=center, **extra_kwargs\n )\n )\n\n def rolling_mean(self, window_size: int, *, min_samples: int, center: bool) -> Self:\n extra_kwargs: dict[str, Any] = (\n {"min_periods": min_samples}\n if self._backend_version < (1, 21, 0)\n else {"min_samples": min_samples}\n )\n return self._with_native(\n self.native.rolling_mean(\n window_size=window_size, center=center, **extra_kwargs\n )\n )\n\n def sort(self, *, descending: bool, nulls_last: bool) -> Self:\n if self._backend_version < (0, 20, 6):\n result = self.native.sort(descending=descending)\n\n if nulls_last:\n is_null = result.is_null()\n result = pl.concat([result.filter(~is_null), result.filter(is_null)])\n else:\n result = self.native.sort(descending=descending, nulls_last=nulls_last)\n\n return self._with_native(result)\n\n def scatter(self, indices: int | Sequence[int], values: Any) -> Self:\n s = self.native.clone().scatter(indices, extract_native(values))\n return self._with_native(s)\n\n def value_counts(\n self, *, sort: bool, parallel: bool, name: str | None, normalize: bool\n ) -> PolarsDataFrame:\n from narwhals._polars.dataframe import PolarsDataFrame\n\n if self._backend_version < (1, 0, 0):\n value_name_ = name or ("proportion" if normalize else "count")\n\n result = self.native.value_counts(sort=sort, parallel=parallel).select(\n **{\n (self.native.name): pl.col(self.native.name),\n value_name_: pl.col("count") / pl.sum("count")\n if normalize\n else pl.col("count"),\n }\n )\n else:\n result = self.native.value_counts(\n sort=sort, parallel=parallel, name=name, normalize=normalize\n )\n return PolarsDataFrame.from_native(result, context=self)\n\n def cum_count(self, *, reverse: bool) -> Self:\n return self._with_native(self.native.cum_count(reverse=reverse))\n\n def __contains__(self, other: Any) -> bool:\n try:\n return self.native.__contains__(other)\n except Exception as e: # noqa: BLE001\n raise catch_polars_exception(e, self._backend_version) from None\n\n def hist( # noqa: C901, PLR0912\n self,\n bins: list[float | int] | None,\n *,\n bin_count: int | None,\n include_breakpoint: bool,\n ) -> PolarsDataFrame:\n from narwhals._polars.dataframe import PolarsDataFrame\n\n if (bins is not None and len(bins) <= 1) or (bin_count == 0): # pragma: no cover\n data: list[pl.Series] = []\n if include_breakpoint:\n data.append(pl.Series("breakpoint", [], dtype=pl.Float64))\n data.append(pl.Series("count", [], dtype=pl.UInt32))\n return PolarsDataFrame.from_native(pl.DataFrame(data), context=self)\n\n if self.native.count() < 1:\n data_dict: dict[str, Sequence[Any] | pl.Series]\n if bins is not None:\n data_dict = {\n "breakpoint": bins[1:],\n "count": pl.zeros(n=len(bins) - 1, dtype=pl.Int64, eager=True),\n }\n elif (bin_count is not None) and bin_count == 1:\n data_dict = {"breakpoint": [1.0], "count": [0]}\n elif (bin_count is not None) and bin_count > 1:\n data_dict = {\n "breakpoint": pl.int_range(1, bin_count + 1, eager=True) / bin_count,\n "count": pl.zeros(n=bin_count, dtype=pl.Int64, eager=True),\n }\n else: # pragma: no cover\n msg = (\n "congratulations, you entered unreachable code - please report a bug"\n )\n raise AssertionError(msg)\n if not include_breakpoint:\n del data_dict["breakpoint"]\n return PolarsDataFrame.from_native(pl.DataFrame(data_dict), context=self)\n\n # polars <1.15 does not adjust the bins when they have equivalent min/max\n # polars <1.5 with bin_count=...\n # returns bins that range from -inf to +inf and has bin_count + 1 bins.\n # for compat: convert `bin_count=` call to `bins=`\n if (self._backend_version < (1, 15)) and (\n bin_count is not None\n ): # pragma: no cover\n lower = cast("float", self.native.min())\n upper = cast("float", self.native.max())\n if lower == upper:\n width = 1 / bin_count\n lower -= 0.5\n upper += 0.5\n else:\n width = (upper - lower) / bin_count\n\n bins = (pl.int_range(0, bin_count + 1, eager=True) * width + lower).to_list()\n bin_count = None\n\n # Polars inconsistently handles NaN values when computing histograms\n # against predefined bins: https://github.com/pola-rs/polars/issues/21082\n series = self.native\n if self._backend_version < (1, 15) or bins is not None:\n series = series.set(series.is_nan(), None)\n\n df = series.hist(\n bins,\n bin_count=bin_count,\n include_category=False,\n include_breakpoint=include_breakpoint,\n )\n\n if not include_breakpoint:\n df.columns = ["count"]\n\n if self._backend_version < (1, 0) and include_breakpoint:\n df = df.rename({"break_point": "breakpoint"})\n\n # polars<1.15 implicitly adds -inf and inf to either end of bins\n if self._backend_version < (1, 15) and bins is not None: # pragma: no cover\n r = pl.int_range(0, len(df))\n df = df.filter((r > 0) & (r < len(df) - 1))\n\n # polars<1.27 makes the lowest bin a left/right closed interval.\n if self._backend_version < (1, 27) and bins is not None:\n df[0, "count"] += (series == bins[0]).sum()\n\n return PolarsDataFrame.from_native(df, context=self)\n\n def to_polars(self) -> pl.Series:\n return self.native\n\n @property\n def dt(self) -> PolarsSeriesDateTimeNamespace:\n return PolarsSeriesDateTimeNamespace(self)\n\n @property\n def str(self) -> PolarsSeriesStringNamespace:\n return PolarsSeriesStringNamespace(self)\n\n @property\n def cat(self) -> PolarsSeriesCatNamespace:\n return PolarsSeriesCatNamespace(self)\n\n @property\n def struct(self) -> PolarsSeriesStructNamespace:\n return PolarsSeriesStructNamespace(self)\n\n __add__: Method[Self]\n __and__: Method[Self]\n __floordiv__: Method[Self]\n __invert__: Method[Self]\n __iter__: Method[Iterator[Any]]\n __mod__: Method[Self]\n __mul__: Method[Self]\n __or__: Method[Self]\n __pow__: Method[Self]\n __radd__: Method[Self]\n __rand__: Method[Self]\n __rfloordiv__: Method[Self]\n __rmod__: Method[Self]\n __rmul__: Method[Self]\n __ror__: Method[Self]\n __rsub__: Method[Self]\n __rtruediv__: Method[Self]\n __sub__: Method[Self]\n __truediv__: Method[Self]\n abs: Method[Self]\n all: Method[bool]\n any: Method[bool]\n arg_max: Method[int]\n arg_min: Method[int]\n arg_true: Method[Self]\n clip: Method[Self]\n count: Method[int]\n cum_max: Method[Self]\n cum_min: Method[Self]\n cum_prod: Method[Self]\n cum_sum: Method[Self]\n diff: Method[Self]\n drop_nulls: Method[Self]\n exp: Method[Self]\n fill_null: Method[Self]\n filter: Method[Self]\n gather_every: Method[Self]\n head: Method[Self]\n is_between: Method[Self]\n is_finite: Method[Self]\n is_first_distinct: Method[Self]\n is_in: Method[Self]\n is_last_distinct: Method[Self]\n is_null: Method[Self]\n is_sorted: Method[bool]\n is_unique: Method[Self]\n item: Method[Any]\n kurtosis: Method[float | None]\n len: Method[int]\n log: Method[Self]\n max: Method[Any]\n mean: Method[float]\n min: Method[Any]\n mode: Method[Self]\n n_unique: Method[int]\n null_count: Method[int]\n quantile: Method[float]\n rank: Method[Self]\n round: Method[Self]\n sample: Method[Self]\n shift: Method[Self]\n skew: Method[float | None]\n sqrt: Method[Self]\n std: Method[float]\n sum: Method[float]\n tail: Method[Self]\n to_arrow: Method[pa.Array[Any]]\n to_frame: Method[PolarsDataFrame]\n to_list: Method[list[Any]]\n to_pandas: Method[pd.Series[Any]]\n unique: Method[Self]\n var: Method[float]\n zip_with: Method[Self]\n\n @property\n def list(self) -> PolarsSeriesListNamespace:\n return PolarsSeriesListNamespace(self)\n\n\nclass PolarsSeriesDateTimeNamespace:\n def __init__(self, series: PolarsSeries) -> None:\n self._compliant_series = series\n\n def __getattr__(self, attr: str) -> Any:\n def func(*args: Any, **kwargs: Any) -> Any:\n pos, kwds = extract_args_kwargs(args, kwargs)\n return self._compliant_series._with_native(\n getattr(self._compliant_series.native.dt, attr)(*pos, **kwds)\n )\n\n return func\n\n\nclass PolarsSeriesStringNamespace:\n def __init__(self, series: PolarsSeries) -> None:\n self._compliant_series = series\n\n def zfill(self, width: int) -> PolarsSeries:\n series = self._compliant_series\n name = series.name\n ns = series.__narwhals_namespace__()\n return series.to_frame().select(ns.col(name).str.zfill(width)).get_column(name)\n\n def __getattr__(self, attr: str) -> Any:\n def func(*args: Any, **kwargs: Any) -> Any:\n pos, kwds = extract_args_kwargs(args, kwargs)\n return self._compliant_series._with_native(\n getattr(self._compliant_series.native.str, attr)(*pos, **kwds)\n )\n\n return func\n\n\nclass PolarsSeriesCatNamespace:\n def __init__(self, series: PolarsSeries) -> None:\n self._compliant_series = series\n\n def __getattr__(self, attr: str) -> Any:\n def func(*args: Any, **kwargs: Any) -> Any:\n pos, kwds = extract_args_kwargs(args, kwargs)\n return self._compliant_series._with_native(\n getattr(self._compliant_series.native.cat, attr)(*pos, **kwds)\n )\n\n return func\n\n\nclass PolarsSeriesListNamespace:\n def __init__(self, series: PolarsSeries) -> None:\n self._series = series\n\n def len(self) -> PolarsSeries:\n native_series = self._series.native\n native_result = native_series.list.len()\n\n if self._series._backend_version < (1, 16): # pragma: no cover\n native_result = pl.select(\n pl.when(~native_series.is_null()).then(native_result).otherwise(None)\n )[native_series.name].cast(pl.UInt32())\n\n elif self._series._backend_version < (1, 17): # pragma: no cover\n native_result = native_series.cast(pl.UInt32())\n\n return self._series._with_native(native_result)\n\n # TODO(FBruzzesi): Remove `pragma: no cover` once other namespace methods are added\n def __getattr__(self, attr: str) -> Any: # pragma: no cover\n def func(*args: Any, **kwargs: Any) -> Any:\n pos, kwds = extract_args_kwargs(args, kwargs)\n return self._series._with_native(\n getattr(self._series.native.list, attr)(*pos, **kwds)\n )\n\n return func\n\n\nclass PolarsSeriesStructNamespace:\n def __init__(self, series: PolarsSeries) -> None:\n self._compliant_series = series\n\n def __getattr__(self, attr: str) -> Any:\n def func(*args: Any, **kwargs: Any) -> Any:\n pos, kwds = extract_args_kwargs(args, kwargs)\n return self._compliant_series._with_native(\n getattr(self._compliant_series.native.struct, attr)(*pos, **kwds)\n )\n\n return func\n | .venv\Lib\site-packages\narwhals\_polars\series.py | series.py | Python | 25,564 | 0.95 | 0.162019 | 0.033019 | python-kit | 773 | 2025-04-11T01:26:33.811891 | MIT | false | 7d20b8855ead6ddf7dab16f6e3461362 |
from __future__ import annotations # pragma: no cover\n\nfrom typing import (\n TYPE_CHECKING, # pragma: no cover\n Union, # pragma: no cover\n)\n\nif TYPE_CHECKING:\n import sys\n from typing import TypeVar\n\n if sys.version_info >= (3, 10):\n from typing import TypeAlias\n else:\n from typing_extensions import TypeAlias\n\n from narwhals._polars.dataframe import PolarsDataFrame, PolarsLazyFrame\n from narwhals._polars.expr import PolarsExpr\n from narwhals._polars.series import PolarsSeries\n\n IntoPolarsExpr: TypeAlias = Union[PolarsExpr, PolarsSeries]\n FrameT = TypeVar("FrameT", PolarsDataFrame, PolarsLazyFrame)\n | .venv\Lib\site-packages\narwhals\_polars\typing.py | typing.py | Python | 655 | 0.95 | 0.090909 | 0 | vue-tools | 757 | 2024-04-25T20:17:57.394038 | BSD-3-Clause | false | 3419781643f8efe55fdd3ad4aefec2d8 |
from __future__ import annotations\n\nfrom functools import lru_cache\nfrom typing import TYPE_CHECKING, Any, TypeVar, overload\n\nimport polars as pl\n\nfrom narwhals._utils import Version, _DeferredIterable, isinstance_or_issubclass\nfrom narwhals.exceptions import (\n ColumnNotFoundError,\n ComputeError,\n DuplicateError,\n InvalidOperationError,\n NarwhalsError,\n ShapeError,\n)\n\nif TYPE_CHECKING:\n from collections.abc import Iterable, Iterator, Mapping\n\n from typing_extensions import TypeIs\n\n from narwhals._utils import _StoresNative\n from narwhals.dtypes import DType\n from narwhals.typing import IntoDType\n\n T = TypeVar("T")\n NativeT = TypeVar(\n "NativeT", bound="pl.DataFrame | pl.LazyFrame | pl.Series | pl.Expr"\n )\n\n\n@overload\ndef extract_native(obj: _StoresNative[NativeT]) -> NativeT: ...\n@overload\ndef extract_native(obj: T) -> T: ...\ndef extract_native(obj: _StoresNative[NativeT] | T) -> NativeT | T:\n return obj.native if _is_compliant_polars(obj) else obj\n\n\ndef _is_compliant_polars(\n obj: _StoresNative[NativeT] | Any,\n) -> TypeIs[_StoresNative[NativeT]]:\n from narwhals._polars.dataframe import PolarsDataFrame, PolarsLazyFrame\n from narwhals._polars.expr import PolarsExpr\n from narwhals._polars.series import PolarsSeries\n\n return isinstance(obj, (PolarsDataFrame, PolarsLazyFrame, PolarsSeries, PolarsExpr))\n\n\ndef extract_args_kwargs(\n args: Iterable[Any], kwds: Mapping[str, Any], /\n) -> tuple[Iterator[Any], dict[str, Any]]:\n it_args = (extract_native(arg) for arg in args)\n return it_args, {k: extract_native(v) for k, v in kwds.items()}\n\n\n@lru_cache(maxsize=16)\ndef native_to_narwhals_dtype( # noqa: C901, PLR0912\n dtype: pl.DataType, version: Version, backend_version: tuple[int, ...]\n) -> DType:\n dtypes = version.dtypes\n if dtype == pl.Float64:\n return dtypes.Float64()\n if dtype == pl.Float32:\n return dtypes.Float32()\n if hasattr(pl, "Int128") and dtype == pl.Int128: # pragma: no cover\n # Not available for Polars pre 1.8.0\n return dtypes.Int128()\n if dtype == pl.Int64:\n return dtypes.Int64()\n if dtype == pl.Int32:\n return dtypes.Int32()\n if dtype == pl.Int16:\n return dtypes.Int16()\n if dtype == pl.Int8:\n return dtypes.Int8()\n if hasattr(pl, "UInt128") and dtype == pl.UInt128: # pragma: no cover\n # Not available for Polars pre 1.8.0\n return dtypes.UInt128()\n if dtype == pl.UInt64:\n return dtypes.UInt64()\n if dtype == pl.UInt32:\n return dtypes.UInt32()\n if dtype == pl.UInt16:\n return dtypes.UInt16()\n if dtype == pl.UInt8:\n return dtypes.UInt8()\n if dtype == pl.String:\n return dtypes.String()\n if dtype == pl.Boolean:\n return dtypes.Boolean()\n if dtype == pl.Object:\n return dtypes.Object()\n if dtype == pl.Categorical:\n return dtypes.Categorical()\n if isinstance_or_issubclass(dtype, pl.Enum):\n if version is Version.V1:\n return dtypes.Enum() # type: ignore[call-arg]\n categories = _DeferredIterable(dtype.categories.to_list)\n return dtypes.Enum(categories)\n if dtype == pl.Date:\n return dtypes.Date()\n if isinstance_or_issubclass(dtype, pl.Datetime):\n return (\n dtypes.Datetime()\n if dtype is pl.Datetime\n else dtypes.Datetime(dtype.time_unit, dtype.time_zone)\n )\n if isinstance_or_issubclass(dtype, pl.Duration):\n return (\n dtypes.Duration()\n if dtype is pl.Duration\n else dtypes.Duration(dtype.time_unit)\n )\n if isinstance_or_issubclass(dtype, pl.Struct):\n fields = [\n dtypes.Field(name, native_to_narwhals_dtype(tp, version, backend_version))\n for name, tp in dtype\n ]\n return dtypes.Struct(fields)\n if isinstance_or_issubclass(dtype, pl.List):\n return dtypes.List(\n native_to_narwhals_dtype(dtype.inner, version, backend_version)\n )\n if isinstance_or_issubclass(dtype, pl.Array):\n outer_shape = dtype.width if backend_version < (0, 20, 30) else dtype.size\n return dtypes.Array(\n native_to_narwhals_dtype(dtype.inner, version, backend_version), outer_shape\n )\n if dtype == pl.Decimal:\n return dtypes.Decimal()\n if dtype == pl.Time:\n return dtypes.Time()\n if dtype == pl.Binary:\n return dtypes.Binary()\n return dtypes.Unknown()\n\n\ndef narwhals_to_native_dtype( # noqa: C901, PLR0912\n dtype: IntoDType, version: Version, backend_version: tuple[int, ...]\n) -> pl.DataType:\n dtypes = version.dtypes\n if dtype == dtypes.Float64:\n return pl.Float64()\n if dtype == dtypes.Float32:\n return pl.Float32()\n if dtype == dtypes.Int128 and hasattr(pl, "Int128"):\n # Not available for Polars pre 1.8.0\n return pl.Int128()\n if dtype == dtypes.Int64:\n return pl.Int64()\n if dtype == dtypes.Int32:\n return pl.Int32()\n if dtype == dtypes.Int16:\n return pl.Int16()\n if dtype == dtypes.Int8:\n return pl.Int8()\n if dtype == dtypes.UInt64:\n return pl.UInt64()\n if dtype == dtypes.UInt32:\n return pl.UInt32()\n if dtype == dtypes.UInt16:\n return pl.UInt16()\n if dtype == dtypes.UInt8:\n return pl.UInt8()\n if dtype == dtypes.String:\n return pl.String()\n if dtype == dtypes.Boolean:\n return pl.Boolean()\n if dtype == dtypes.Object: # pragma: no cover\n return pl.Object()\n if dtype == dtypes.Categorical:\n return pl.Categorical()\n if isinstance_or_issubclass(dtype, dtypes.Enum):\n if version is Version.V1:\n msg = "Converting to Enum is not supported in narwhals.stable.v1"\n raise NotImplementedError(msg)\n if isinstance(dtype, dtypes.Enum):\n return pl.Enum(dtype.categories)\n msg = "Can not cast / initialize Enum without categories present"\n raise ValueError(msg)\n if dtype == dtypes.Date:\n return pl.Date()\n if dtype == dtypes.Time:\n return pl.Time()\n if dtype == dtypes.Binary:\n return pl.Binary()\n if dtype == dtypes.Decimal:\n msg = "Casting to Decimal is not supported yet."\n raise NotImplementedError(msg)\n if isinstance_or_issubclass(dtype, dtypes.Datetime):\n return pl.Datetime(dtype.time_unit, dtype.time_zone) # type: ignore[arg-type]\n if isinstance_or_issubclass(dtype, dtypes.Duration):\n return pl.Duration(dtype.time_unit) # type: ignore[arg-type]\n if isinstance_or_issubclass(dtype, dtypes.List):\n return pl.List(narwhals_to_native_dtype(dtype.inner, version, backend_version))\n if isinstance_or_issubclass(dtype, dtypes.Struct):\n fields = [\n pl.Field(\n field.name,\n narwhals_to_native_dtype(field.dtype, version, backend_version),\n )\n for field in dtype.fields\n ]\n return pl.Struct(fields)\n if isinstance_or_issubclass(dtype, dtypes.Array): # pragma: no cover\n size = dtype.size\n kwargs = {"width": size} if backend_version < (0, 20, 30) else {"shape": size}\n return pl.Array(\n narwhals_to_native_dtype(dtype.inner, version, backend_version), **kwargs\n )\n return pl.Unknown() # pragma: no cover\n\n\ndef _is_polars_exception(exception: Exception, backend_version: tuple[int, ...]) -> bool:\n if backend_version >= (1,):\n # Old versions of Polars didn't have PolarsError.\n return isinstance(exception, pl.exceptions.PolarsError)\n # Last attempt, for old Polars versions.\n return "polars.exceptions" in str(type(exception)) # pragma: no cover\n\n\ndef _is_cudf_exception(exception: Exception) -> bool:\n # These exceptions are raised when running polars on GPUs via cuDF\n return str(exception).startswith("CUDF failure")\n\n\ndef catch_polars_exception(\n exception: Exception, backend_version: tuple[int, ...]\n) -> NarwhalsError | Exception:\n if isinstance(exception, pl.exceptions.ColumnNotFoundError):\n return ColumnNotFoundError(str(exception))\n elif isinstance(exception, pl.exceptions.ShapeError):\n return ShapeError(str(exception))\n elif isinstance(exception, pl.exceptions.InvalidOperationError):\n return InvalidOperationError(str(exception))\n elif isinstance(exception, pl.exceptions.DuplicateError):\n return DuplicateError(str(exception))\n elif isinstance(exception, pl.exceptions.ComputeError):\n return ComputeError(str(exception))\n if _is_polars_exception(exception, backend_version) or _is_cudf_exception(exception):\n return NarwhalsError(str(exception)) # pragma: no cover\n # Just return exception as-is.\n return exception\n | .venv\Lib\site-packages\narwhals\_polars\utils.py | utils.py | Python | 8,836 | 0.95 | 0.330612 | 0.031674 | awesome-app | 21 | 2024-06-20T20:31:58.655259 | MIT | false | 50f41d0d9eb496ce8d8b2718b16d7add |
\n\n | .venv\Lib\site-packages\narwhals\_polars\__pycache__\dataframe.cpython-313.pyc | dataframe.cpython-313.pyc | Other | 30,388 | 0.95 | 0.004444 | 0.004762 | react-lib | 503 | 2025-06-25T21:15:55.919045 | BSD-3-Clause | false | b154d91f1294bd91f76f5631912ac814 |
\n\n | .venv\Lib\site-packages\narwhals\_polars\__pycache__\expr.cpython-313.pyc | expr.cpython-313.pyc | Other | 25,943 | 0.95 | 0.006329 | 0 | react-lib | 862 | 2024-07-15T22:15:17.558882 | BSD-3-Clause | false | 8c6bd310bfac772392330403f434a13f |
\n\n | .venv\Lib\site-packages\narwhals\_polars\__pycache__\group_by.cpython-313.pyc | group_by.cpython-313.pyc | Other | 4,979 | 0.8 | 0 | 0 | react-lib | 708 | 2023-07-17T16:13:35.250475 | Apache-2.0 | false | a810a08046dfbca8ccce691fd1742724 |
\n\n | .venv\Lib\site-packages\narwhals\_polars\__pycache__\namespace.cpython-313.pyc | namespace.cpython-313.pyc | Other | 18,466 | 0.95 | 0.004695 | 0.009804 | node-utils | 475 | 2023-10-03T05:11:42.362812 | BSD-3-Clause | false | 83159c87504866b97ecfe30d4b3e43f6 |
\n\n | .venv\Lib\site-packages\narwhals\_polars\__pycache__\series.cpython-313.pyc | series.cpython-313.pyc | Other | 35,170 | 0.95 | 0.003876 | 0.016194 | react-lib | 455 | 2025-03-28T02:23:05.935096 | MIT | false | d84bf325f68609e7975116932af0d1e5 |
\n\n | .venv\Lib\site-packages\narwhals\_polars\__pycache__\typing.cpython-313.pyc | typing.cpython-313.pyc | Other | 862 | 0.7 | 0 | 0 | vue-tools | 304 | 2024-08-08T11:23:43.612847 | BSD-3-Clause | false | 333fbf322a69e8ab412ba8ec79607c9a |
\n\n | .venv\Lib\site-packages\narwhals\_polars\__pycache__\utils.cpython-313.pyc | utils.cpython-313.pyc | Other | 13,361 | 0.8 | 0 | 0 | vue-tools | 587 | 2025-02-01T17:46:56.352085 | MIT | false | a0d7c7628992d3dbbc2183fe7ba63776 |
\n\n | .venv\Lib\site-packages\narwhals\_polars\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 191 | 0.7 | 0 | 0 | vue-tools | 355 | 2025-06-09T23:09:46.623597 | BSD-3-Clause | false | be81028761ac05601941b1465f618666 |
from __future__ import annotations\n\nimport warnings\nfrom functools import reduce\nfrom operator import and_\nfrom typing import TYPE_CHECKING, Any\n\nfrom narwhals._namespace import is_native_spark_like\nfrom narwhals._spark_like.utils import (\n evaluate_exprs,\n import_functions,\n import_native_dtypes,\n import_window,\n native_to_narwhals_dtype,\n)\nfrom narwhals._utils import (\n Implementation,\n find_stacklevel,\n generate_temporary_column_name,\n not_implemented,\n parse_columns_to_drop,\n parse_version,\n validate_backend_version,\n)\nfrom narwhals.exceptions import InvalidOperationError\nfrom narwhals.typing import CompliantLazyFrame\n\nif TYPE_CHECKING:\n from collections.abc import Iterator, Mapping, Sequence\n from types import ModuleType\n\n import pyarrow as pa\n from sqlframe.base.column import Column\n from sqlframe.base.dataframe import BaseDataFrame\n from sqlframe.base.window import Window\n from typing_extensions import Self, TypeAlias, TypeIs\n\n from narwhals._compliant.typing import CompliantDataFrameAny\n from narwhals._spark_like.expr import SparkLikeExpr\n from narwhals._spark_like.group_by import SparkLikeLazyGroupBy\n from narwhals._spark_like.namespace import SparkLikeNamespace\n from narwhals._utils import Version, _FullContext\n from narwhals.dataframe import LazyFrame\n from narwhals.dtypes import DType\n from narwhals.typing import JoinStrategy, LazyUniqueKeepStrategy\n\n SQLFrameDataFrame = BaseDataFrame[Any, Any, Any, Any, Any]\n\nIncomplete: TypeAlias = Any # pragma: no cover\n"""Marker for working code that fails type checking."""\n\n\nclass SparkLikeLazyFrame(\n CompliantLazyFrame[\n "SparkLikeExpr", "SQLFrameDataFrame", "LazyFrame[SQLFrameDataFrame]"\n ]\n):\n def __init__(\n self,\n native_dataframe: SQLFrameDataFrame,\n *,\n backend_version: tuple[int, ...],\n version: Version,\n implementation: Implementation,\n ) -> None:\n self._native_frame: SQLFrameDataFrame = native_dataframe\n self._backend_version = backend_version\n self._implementation = implementation\n self._version = version\n self._cached_schema: dict[str, DType] | None = None\n self._cached_columns: list[str] | None = None\n validate_backend_version(self._implementation, self._backend_version)\n\n @property\n def _F(self): # type: ignore[no-untyped-def] # noqa: ANN202, N802\n if TYPE_CHECKING:\n from sqlframe.base import functions\n\n return functions\n else:\n return import_functions(self._implementation)\n\n @property\n def _native_dtypes(self): # type: ignore[no-untyped-def] # noqa: ANN202\n if TYPE_CHECKING:\n from sqlframe.base import types\n\n return types\n else:\n return import_native_dtypes(self._implementation)\n\n @property\n def _Window(self) -> type[Window]: # noqa: N802\n if TYPE_CHECKING:\n from sqlframe.base.window import Window\n\n return Window\n else:\n return import_window(self._implementation)\n\n @staticmethod\n def _is_native(obj: SQLFrameDataFrame | Any) -> TypeIs[SQLFrameDataFrame]:\n return is_native_spark_like(obj)\n\n @classmethod\n def from_native(cls, data: SQLFrameDataFrame, /, *, context: _FullContext) -> Self:\n return cls(\n data,\n backend_version=context._backend_version,\n version=context._version,\n implementation=context._implementation,\n )\n\n def to_narwhals(self) -> LazyFrame[SQLFrameDataFrame]:\n return self._version.lazyframe(self, level="lazy")\n\n def __native_namespace__(self) -> ModuleType: # pragma: no cover\n return self._implementation.to_native_namespace()\n\n def __narwhals_namespace__(self) -> SparkLikeNamespace:\n from narwhals._spark_like.namespace import SparkLikeNamespace\n\n return SparkLikeNamespace(\n backend_version=self._backend_version,\n version=self._version,\n implementation=self._implementation,\n )\n\n def __narwhals_lazyframe__(self) -> Self:\n return self\n\n def _with_version(self, version: Version) -> Self:\n return self.__class__(\n self.native,\n backend_version=self._backend_version,\n version=version,\n implementation=self._implementation,\n )\n\n def _with_native(self, df: SQLFrameDataFrame) -> Self:\n return self.__class__(\n df,\n backend_version=self._backend_version,\n version=self._version,\n implementation=self._implementation,\n )\n\n def _to_arrow_schema(self) -> pa.Schema: # pragma: no cover\n import pyarrow as pa # ignore-banned-import\n\n from narwhals._arrow.utils import narwhals_to_native_dtype\n\n schema: list[tuple[str, pa.DataType]] = []\n nw_schema = self.collect_schema()\n native_schema = self.native.schema\n for key, value in nw_schema.items():\n try:\n native_dtype = narwhals_to_native_dtype(value, self._version)\n except Exception as exc: # noqa: BLE001,PERF203\n native_spark_dtype = native_schema[key].dataType # type: ignore[index]\n # If we can't convert the type, just set it to `pa.null`, and warn.\n # Avoid the warning if we're starting from PySpark's void type.\n # We can avoid the check when we introduce `nw.Null` dtype.\n null_type = self._native_dtypes.NullType # pyright: ignore[reportAttributeAccessIssue]\n if not isinstance(native_spark_dtype, null_type):\n warnings.warn(\n f"Could not convert dtype {native_spark_dtype} to PyArrow dtype, {exc!r}",\n stacklevel=find_stacklevel(),\n )\n schema.append((key, pa.null()))\n else:\n schema.append((key, native_dtype))\n return pa.schema(schema)\n\n def _collect_to_arrow(self) -> pa.Table:\n if self._implementation.is_pyspark() and self._backend_version < (4,):\n import pyarrow as pa # ignore-banned-import\n\n try:\n return pa.Table.from_batches(self.native._collect_as_arrow())\n except ValueError as exc:\n if "at least one RecordBatch" in str(exc):\n # Empty dataframe\n\n data: dict[str, list[Any]] = {k: [] for k in self.columns}\n pa_schema = self._to_arrow_schema()\n return pa.Table.from_pydict(data, schema=pa_schema)\n else: # pragma: no cover\n raise\n elif self._implementation.is_pyspark_connect() and self._backend_version < (4,):\n import pyarrow as pa # ignore-banned-import\n\n pa_schema = self._to_arrow_schema()\n return pa.Table.from_pandas(self.native.toPandas(), schema=pa_schema)\n else:\n return self.native.toArrow()\n\n def _iter_columns(self) -> Iterator[Column]:\n for col in self.columns:\n yield self._F.col(col)\n\n @property\n def columns(self) -> list[str]:\n if self._cached_columns is None:\n self._cached_columns = (\n list(self.schema)\n if self._cached_schema is not None\n else self.native.columns\n )\n return self._cached_columns\n\n def collect(\n self, backend: ModuleType | Implementation | str | None, **kwargs: Any\n ) -> CompliantDataFrameAny:\n if backend is Implementation.PANDAS:\n import pandas as pd # ignore-banned-import\n\n from narwhals._pandas_like.dataframe import PandasLikeDataFrame\n\n return PandasLikeDataFrame(\n self.native.toPandas(),\n implementation=Implementation.PANDAS,\n backend_version=parse_version(pd),\n version=self._version,\n validate_column_names=True,\n )\n\n elif backend is None or backend is Implementation.PYARROW:\n import pyarrow as pa # ignore-banned-import\n\n from narwhals._arrow.dataframe import ArrowDataFrame\n\n return ArrowDataFrame(\n self._collect_to_arrow(),\n backend_version=parse_version(pa),\n version=self._version,\n validate_column_names=True,\n )\n\n elif backend is Implementation.POLARS:\n import polars as pl # ignore-banned-import\n import pyarrow as pa # ignore-banned-import\n\n from narwhals._polars.dataframe import PolarsDataFrame\n\n return PolarsDataFrame(\n pl.from_arrow(self._collect_to_arrow()), # type: ignore[arg-type]\n backend_version=parse_version(pl),\n version=self._version,\n )\n\n msg = f"Unsupported `backend` value: {backend}" # pragma: no cover\n raise ValueError(msg) # pragma: no cover\n\n def simple_select(self, *column_names: str) -> Self:\n return self._with_native(self.native.select(*column_names))\n\n def aggregate(self, *exprs: SparkLikeExpr) -> Self:\n new_columns = evaluate_exprs(self, *exprs)\n\n new_columns_list = [col.alias(col_name) for col_name, col in new_columns]\n return self._with_native(self.native.agg(*new_columns_list))\n\n def select(self, *exprs: SparkLikeExpr) -> Self:\n new_columns = evaluate_exprs(self, *exprs)\n new_columns_list = [col.alias(col_name) for (col_name, col) in new_columns]\n return self._with_native(self.native.select(*new_columns_list))\n\n def with_columns(self, *exprs: SparkLikeExpr) -> Self:\n new_columns = evaluate_exprs(self, *exprs)\n return self._with_native(self.native.withColumns(dict(new_columns)))\n\n def filter(self, predicate: SparkLikeExpr) -> Self:\n # `[0]` is safe as the predicate's expression only returns a single column\n condition = predicate._call(self)[0]\n spark_df = self.native.where(condition)\n return self._with_native(spark_df)\n\n @property\n def schema(self) -> dict[str, DType]:\n if self._cached_schema is None:\n self._cached_schema = {\n field.name: native_to_narwhals_dtype(\n field.dataType,\n self._version,\n self._native_dtypes,\n self.native.sparkSession,\n )\n for field in self.native.schema\n }\n return self._cached_schema\n\n def collect_schema(self) -> dict[str, DType]:\n return self.schema\n\n def drop(self, columns: Sequence[str], *, strict: bool) -> Self:\n columns_to_drop = parse_columns_to_drop(self, columns, strict=strict)\n return self._with_native(self.native.drop(*columns_to_drop))\n\n def head(self, n: int) -> Self:\n return self._with_native(self.native.limit(n))\n\n def group_by(\n self, keys: Sequence[str] | Sequence[SparkLikeExpr], *, drop_null_keys: bool\n ) -> SparkLikeLazyGroupBy:\n from narwhals._spark_like.group_by import SparkLikeLazyGroupBy\n\n return SparkLikeLazyGroupBy(self, keys, drop_null_keys=drop_null_keys)\n\n def sort(self, *by: str, descending: bool | Sequence[bool], nulls_last: bool) -> Self:\n if isinstance(descending, bool):\n descending = [descending] * len(by)\n\n if nulls_last:\n sort_funcs = (\n self._F.desc_nulls_last if d else self._F.asc_nulls_last\n for d in descending\n )\n else:\n sort_funcs = (\n self._F.desc_nulls_first if d else self._F.asc_nulls_first\n for d in descending\n )\n\n sort_cols = [sort_f(col) for col, sort_f in zip(by, sort_funcs)]\n return self._with_native(self.native.sort(*sort_cols))\n\n def drop_nulls(self, subset: Sequence[str] | None) -> Self:\n subset = list(subset) if subset else None\n return self._with_native(self.native.dropna(subset=subset))\n\n def rename(self, mapping: Mapping[str, str]) -> Self:\n rename_mapping = {\n colname: mapping.get(colname, colname) for colname in self.columns\n }\n return self._with_native(\n self.native.select(\n [self._F.col(old).alias(new) for old, new in rename_mapping.items()]\n )\n )\n\n def unique(\n self, subset: Sequence[str] | None, *, keep: LazyUniqueKeepStrategy\n ) -> Self:\n if subset and (error := self._check_columns_exist(subset)):\n raise error\n subset = list(subset) if subset else None\n if keep == "none":\n tmp = generate_temporary_column_name(8, self.columns)\n window = self._Window.partitionBy(subset or self.columns)\n df = (\n self.native.withColumn(tmp, self._F.count("*").over(window))\n .filter(self._F.col(tmp) == self._F.lit(1))\n .drop(self._F.col(tmp))\n )\n return self._with_native(df)\n return self._with_native(self.native.dropDuplicates(subset=subset))\n\n def join(\n self,\n other: Self,\n how: JoinStrategy,\n left_on: Sequence[str] | None,\n right_on: Sequence[str] | None,\n suffix: str,\n ) -> Self:\n left_columns = self.columns\n right_columns = other.columns\n\n right_on_: list[str] = list(right_on) if right_on is not None else []\n left_on_: list[str] = list(left_on) if left_on is not None else []\n\n # create a mapping for columns on other\n # `right_on` columns will be renamed as `left_on`\n # the remaining columns will be either added the suffix or left unchanged.\n right_cols_to_rename = (\n [c for c in right_columns if c not in right_on_]\n if how != "full"\n else right_columns\n )\n\n rename_mapping = {\n **dict(zip(right_on_, left_on_)),\n **{\n colname: f"{colname}{suffix}" if colname in left_columns else colname\n for colname in right_cols_to_rename\n },\n }\n other_native = other.native.select(\n [self._F.col(old).alias(new) for old, new in rename_mapping.items()]\n )\n\n # If how in {"semi", "anti"}, then resulting columns are same as left columns\n # Otherwise, we add the right columns with the new mapping, while keeping the\n # original order of right_columns.\n col_order = left_columns.copy()\n\n if how in {"inner", "left", "cross"}:\n col_order.extend(\n rename_mapping[colname]\n for colname in right_columns\n if colname not in right_on_\n )\n elif how == "full":\n col_order.extend(rename_mapping.values())\n\n right_on_remapped = [rename_mapping[c] for c in right_on_]\n on_ = (\n reduce(\n and_,\n (\n getattr(self.native, left_key) == getattr(other_native, right_key)\n for left_key, right_key in zip(left_on_, right_on_remapped)\n ),\n )\n if how == "full"\n else None\n if how == "cross"\n else left_on_\n )\n how_native = "full_outer" if how == "full" else how\n return self._with_native(\n self.native.join(other_native, on=on_, how=how_native).select(col_order)\n )\n\n def explode(self, columns: Sequence[str]) -> Self:\n dtypes = self._version.dtypes\n\n schema = self.collect_schema()\n for col_to_explode in columns:\n dtype = schema[col_to_explode]\n\n if dtype != dtypes.List:\n msg = (\n f"`explode` operation not supported for dtype `{dtype}`, "\n "expected List type"\n )\n raise InvalidOperationError(msg)\n\n column_names = self.columns\n\n if len(columns) != 1:\n msg = (\n "Exploding on multiple columns is not supported with SparkLike backend since "\n "we cannot guarantee that the exploded columns have matching element counts."\n )\n raise NotImplementedError(msg)\n\n if self._implementation.is_pyspark() or self._implementation.is_pyspark_connect():\n return self._with_native(\n self.native.select(\n *[\n self._F.col(col_name).alias(col_name)\n if col_name != columns[0]\n else self._F.explode_outer(col_name).alias(col_name)\n for col_name in column_names\n ]\n )\n )\n elif self._implementation.is_sqlframe():\n # Not every sqlframe dialect supports `explode_outer` function\n # (see https://github.com/eakmanrq/sqlframe/blob/3cb899c515b101ff4c197d84b34fae490d0ed257/sqlframe/base/functions.py#L2288-L2289)\n # therefore we simply explode the array column which will ignore nulls and\n # zero sized arrays, and append these specific condition with nulls (to\n # match polars behavior).\n\n def null_condition(col_name: str) -> Column:\n return self._F.isnull(col_name) | (self._F.array_size(col_name) == 0)\n\n return self._with_native(\n self.native.select(\n *[\n self._F.col(col_name).alias(col_name)\n if col_name != columns[0]\n else self._F.explode(col_name).alias(col_name)\n for col_name in column_names\n ]\n ).union(\n self.native.filter(null_condition(columns[0])).select(\n *[\n self._F.col(col_name).alias(col_name)\n if col_name != columns[0]\n else self._F.lit(None).alias(col_name)\n for col_name in column_names\n ]\n )\n )\n )\n else: # pragma: no cover\n msg = "Unreachable code, please report an issue at https://github.com/narwhals-dev/narwhals/issues"\n raise AssertionError(msg)\n\n def unpivot(\n self,\n on: Sequence[str] | None,\n index: Sequence[str] | None,\n variable_name: str,\n value_name: str,\n ) -> Self:\n if self._implementation.is_sqlframe():\n if variable_name == "":\n msg = "`variable_name` cannot be empty string for sqlframe backend."\n raise NotImplementedError(msg)\n\n if value_name == "":\n msg = "`value_name` cannot be empty string for sqlframe backend."\n raise NotImplementedError(msg)\n else: # pragma: no cover\n pass\n\n ids = tuple(index) if index else ()\n values = (\n tuple(set(self.columns).difference(set(ids))) if on is None else tuple(on)\n )\n unpivoted_native_frame = self.native.unpivot(\n ids=ids,\n values=values,\n variableColumnName=variable_name,\n valueColumnName=value_name,\n )\n if index is None:\n unpivoted_native_frame = unpivoted_native_frame.drop(*ids)\n return self._with_native(unpivoted_native_frame)\n\n def with_row_index(self, name: str, order_by: Sequence[str]) -> Self:\n row_index_expr = (\n self._F.row_number().over(\n self._Window.partitionBy(self._F.lit(1)).orderBy(*order_by)\n )\n - 1\n ).alias(name)\n return self._with_native(self.native.select(row_index_expr, *self.columns))\n\n gather_every = not_implemented.deprecated(\n "`LazyFrame.gather_every` is deprecated and will be removed in a future version."\n )\n join_asof = not_implemented()\n tail = not_implemented.deprecated(\n "`LazyFrame.tail` is deprecated and will be removed in a future version."\n )\n | .venv\Lib\site-packages\narwhals\_spark_like\dataframe.py | dataframe.py | Python | 20,325 | 0.95 | 0.205556 | 0.04793 | python-kit | 684 | 2024-10-18T03:56:38.165225 | GPL-3.0 | false | 2f00eb736aef2f7a26a565a105dfe677 |
from __future__ import annotations\n\nimport operator\nfrom typing import TYPE_CHECKING, Any, Callable, ClassVar, Literal, cast\n\nfrom narwhals._compliant import LazyExpr\nfrom narwhals._compliant.window import WindowInputs\nfrom narwhals._expression_parsing import (\n ExprKind,\n combine_alias_output_names,\n combine_evaluate_output_names,\n)\nfrom narwhals._spark_like.expr_dt import SparkLikeExprDateTimeNamespace\nfrom narwhals._spark_like.expr_list import SparkLikeExprListNamespace\nfrom narwhals._spark_like.expr_str import SparkLikeExprStringNamespace\nfrom narwhals._spark_like.expr_struct import SparkLikeExprStructNamespace\nfrom narwhals._spark_like.utils import (\n import_functions,\n import_native_dtypes,\n import_window,\n narwhals_to_native_dtype,\n true_divide,\n)\nfrom narwhals._utils import Implementation, not_implemented, parse_version\nfrom narwhals.dependencies import get_pyspark\n\nif TYPE_CHECKING:\n from collections.abc import Iterable, Iterator, Mapping, Sequence\n\n from sqlframe.base.column import Column\n from sqlframe.base.window import Window, WindowSpec\n from typing_extensions import Self, TypeAlias\n\n from narwhals._compliant.typing import (\n AliasNames,\n EvalNames,\n EvalSeries,\n WindowFunction,\n )\n from narwhals._expression_parsing import ExprMetadata\n from narwhals._spark_like.dataframe import SparkLikeLazyFrame\n from narwhals._spark_like.namespace import SparkLikeNamespace\n from narwhals._utils import Version, _FullContext\n from narwhals.typing import (\n FillNullStrategy,\n IntoDType,\n NonNestedLiteral,\n NumericLiteral,\n RankMethod,\n TemporalLiteral,\n )\n\n NativeRankMethod: TypeAlias = Literal["rank", "dense_rank", "row_number"]\n SparkWindowFunction = WindowFunction[SparkLikeLazyFrame, Column]\n SparkWindowInputs = WindowInputs[Column]\n\n\nclass SparkLikeExpr(LazyExpr["SparkLikeLazyFrame", "Column"]):\n _REMAP_RANK_METHOD: ClassVar[Mapping[RankMethod, NativeRankMethod]] = {\n "min": "rank",\n "max": "rank",\n "average": "rank",\n "dense": "dense_rank",\n "ordinal": "row_number",\n }\n\n def __init__(\n self,\n call: EvalSeries[SparkLikeLazyFrame, Column],\n window_function: SparkWindowFunction | None = None,\n *,\n evaluate_output_names: EvalNames[SparkLikeLazyFrame],\n alias_output_names: AliasNames | None,\n backend_version: tuple[int, ...],\n version: Version,\n implementation: Implementation,\n ) -> None:\n self._call = call\n self._evaluate_output_names = evaluate_output_names\n self._alias_output_names = alias_output_names\n self._backend_version = backend_version\n self._version = version\n self._implementation = implementation\n self._metadata: ExprMetadata | None = None\n self._window_function: SparkWindowFunction | None = window_function\n\n @property\n def window_function(self) -> SparkWindowFunction:\n def default_window_func(\n df: SparkLikeLazyFrame, window_inputs: SparkWindowInputs\n ) -> list[Column]:\n assert not window_inputs.order_by # noqa: S101\n return [\n expr.over(self.partition_by(*window_inputs.partition_by))\n for expr in self(df)\n ]\n\n return self._window_function or default_window_func\n\n def __call__(self, df: SparkLikeLazyFrame) -> Sequence[Column]:\n return self._call(df)\n\n def broadcast(self, kind: Literal[ExprKind.AGGREGATION, ExprKind.LITERAL]) -> Self:\n if kind is ExprKind.LITERAL:\n return self\n return self.over([self._F.lit(1)], [])\n\n @property\n def _F(self): # type: ignore[no-untyped-def] # noqa: ANN202, N802\n if TYPE_CHECKING:\n from sqlframe.base import functions\n\n return functions\n else:\n return import_functions(self._implementation)\n\n @property\n def _native_dtypes(self): # type: ignore[no-untyped-def] # noqa: ANN202\n if TYPE_CHECKING:\n from sqlframe.base import types\n\n return types\n else:\n return import_native_dtypes(self._implementation)\n\n @property\n def _Window(self) -> type[Window]: # noqa: N802\n if TYPE_CHECKING:\n from sqlframe.base.window import Window\n\n return Window\n else:\n return import_window(self._implementation)\n\n def _sort(\n self, *cols: Column | str, descending: bool = False, nulls_last: bool = False\n ) -> Iterator[Column]:\n F = self._F # noqa: N806\n mapping = {\n (False, False): F.asc_nulls_first,\n (False, True): F.asc_nulls_last,\n (True, False): F.desc_nulls_first,\n (True, True): F.desc_nulls_last,\n }\n sort = mapping[(descending, nulls_last)]\n yield from (sort(col) for col in cols)\n\n def partition_by(self, *cols: Column | str) -> WindowSpec:\n """Wraps `Window().paritionBy`, with default and `WindowInputs` handling."""\n return self._Window.partitionBy(*cols or [self._F.lit(1)])\n\n def __narwhals_expr__(self) -> None: ...\n\n def __narwhals_namespace__(self) -> SparkLikeNamespace: # pragma: no cover\n # Unused, just for compatibility with PandasLikeExpr\n from narwhals._spark_like.namespace import SparkLikeNamespace\n\n return SparkLikeNamespace(\n backend_version=self._backend_version,\n version=self._version,\n implementation=self._implementation,\n )\n\n def _with_window_function(self, window_function: SparkWindowFunction) -> Self:\n return self.__class__(\n self._call,\n window_function,\n evaluate_output_names=self._evaluate_output_names,\n alias_output_names=self._alias_output_names,\n backend_version=self._backend_version,\n version=self._version,\n implementation=self._implementation,\n )\n\n @classmethod\n def _alias_native(cls, expr: Column, name: str) -> Column:\n return expr.alias(name)\n\n def _cum_window_func(\n self,\n *,\n reverse: bool,\n func_name: Literal["sum", "max", "min", "count", "product"],\n ) -> SparkWindowFunction:\n def func(df: SparkLikeLazyFrame, inputs: SparkWindowInputs) -> Sequence[Column]:\n window = (\n self.partition_by(*inputs.partition_by)\n .orderBy(\n *self._sort(*inputs.order_by, descending=reverse, nulls_last=reverse)\n )\n .rowsBetween(self._Window.unboundedPreceding, 0)\n )\n return [\n getattr(self._F, func_name)(expr).over(window) for expr in self._call(df)\n ]\n\n return func\n\n def _rolling_window_func(\n self,\n *,\n func_name: Literal["sum", "mean", "std", "var"],\n center: bool,\n window_size: int,\n min_samples: int,\n ddof: int | None = None,\n ) -> SparkWindowFunction:\n supported_funcs = ["sum", "mean", "std", "var"]\n if center:\n half = (window_size - 1) // 2\n remainder = (window_size - 1) % 2\n start = self._Window.currentRow - half - remainder\n end = self._Window.currentRow + half\n else:\n start = self._Window.currentRow - window_size + 1\n end = self._Window.currentRow\n\n def func(df: SparkLikeLazyFrame, inputs: SparkWindowInputs) -> Sequence[Column]:\n window = (\n self.partition_by(*inputs.partition_by)\n .orderBy(*self._sort(*inputs.order_by))\n .rowsBetween(start, end)\n )\n if func_name in {"sum", "mean"}:\n func_: str = func_name\n elif func_name == "var" and ddof == 0:\n func_ = "var_pop"\n elif func_name in "var" and ddof == 1:\n func_ = "var_samp"\n elif func_name == "std" and ddof == 0:\n func_ = "stddev_pop"\n elif func_name == "std" and ddof == 1:\n func_ = "stddev_samp"\n elif func_name in {"var", "std"}: # pragma: no cover\n msg = f"Only ddof=0 and ddof=1 are currently supported for rolling_{func_name}."\n raise ValueError(msg)\n else: # pragma: no cover\n msg = f"Only the following functions are supported: {supported_funcs}.\nGot: {func_name}."\n raise ValueError(msg)\n return [\n self._F.when(\n self._F.count(expr).over(window) >= min_samples,\n getattr(self._F, func_)(expr).over(window),\n )\n for expr in self._call(df)\n ]\n\n return func\n\n @classmethod\n def from_column_names(\n cls: type[Self],\n evaluate_column_names: EvalNames[SparkLikeLazyFrame],\n /,\n *,\n context: _FullContext,\n ) -> Self:\n def func(df: SparkLikeLazyFrame) -> list[Column]:\n return [df._F.col(col_name) for col_name in evaluate_column_names(df)]\n\n return cls(\n func,\n evaluate_output_names=evaluate_column_names,\n alias_output_names=None,\n backend_version=context._backend_version,\n version=context._version,\n implementation=context._implementation,\n )\n\n @classmethod\n def from_column_indices(cls, *column_indices: int, context: _FullContext) -> Self:\n def func(df: SparkLikeLazyFrame) -> list[Column]:\n columns = df.columns\n return [df._F.col(columns[i]) for i in column_indices]\n\n return cls(\n func,\n evaluate_output_names=cls._eval_names_indices(column_indices),\n alias_output_names=None,\n backend_version=context._backend_version,\n version=context._version,\n implementation=context._implementation,\n )\n\n @classmethod\n def _from_elementwise_horizontal_op(\n cls, func: Callable[[Iterable[Column]], Column], *exprs: Self\n ) -> Self:\n def call(df: SparkLikeLazyFrame) -> list[Column]:\n cols = (col for _expr in exprs for col in _expr(df))\n return [func(cols)]\n\n def window_function(\n df: SparkLikeLazyFrame, window_inputs: SparkWindowInputs\n ) -> list[Column]:\n cols = (\n col for _expr in exprs for col in _expr.window_function(df, window_inputs)\n )\n return [func(cols)]\n\n context = exprs[0]\n return cls(\n call=call,\n window_function=window_function,\n evaluate_output_names=combine_evaluate_output_names(*exprs),\n alias_output_names=combine_alias_output_names(*exprs),\n backend_version=context._backend_version,\n version=context._version,\n implementation=context._implementation,\n )\n\n def _callable_to_eval_series(\n self, call: Callable[..., Column], /, **expressifiable_args: Self | Any\n ) -> EvalSeries[SparkLikeLazyFrame, Column]:\n def func(df: SparkLikeLazyFrame) -> list[Column]:\n native_series_list = self(df)\n other_native_series = {\n key: df._evaluate_expr(value)\n if self._is_expr(value)\n else self._F.lit(value)\n for key, value in expressifiable_args.items()\n }\n return [\n call(native_series, **other_native_series)\n for native_series in native_series_list\n ]\n\n return func\n\n def _push_down_window_function(\n self, call: Callable[..., Column], /, **expressifiable_args: Self | Any\n ) -> SparkWindowFunction:\n def window_f(\n df: SparkLikeLazyFrame, window_inputs: SparkWindowInputs\n ) -> Sequence[Column]:\n # If a function `f` is elementwise, and `g` is another function, then\n # - `f(g) over (window)`\n # - `f(g over (window))\n # are equivalent.\n # Make sure to only use with if `call` is elementwise!\n native_series_list = self.window_function(df, window_inputs)\n other_native_series = {\n key: df._evaluate_window_expr(value, window_inputs)\n if self._is_expr(value)\n else self._F.lit(value)\n for key, value in expressifiable_args.items()\n }\n return [\n call(native_series, **other_native_series)\n for native_series in native_series_list\n ]\n\n return window_f\n\n def _with_callable(\n self, call: Callable[..., Column], /, **expressifiable_args: Self | Any\n ) -> Self:\n return self.__class__(\n self._callable_to_eval_series(call, **expressifiable_args),\n evaluate_output_names=self._evaluate_output_names,\n alias_output_names=self._alias_output_names,\n backend_version=self._backend_version,\n version=self._version,\n implementation=self._implementation,\n )\n\n def _with_elementwise(\n self, call: Callable[..., Column], /, **expressifiable_args: Self | Any\n ) -> Self:\n return self.__class__(\n self._callable_to_eval_series(call, **expressifiable_args),\n self._push_down_window_function(call, **expressifiable_args),\n evaluate_output_names=self._evaluate_output_names,\n alias_output_names=self._alias_output_names,\n backend_version=self._backend_version,\n version=self._version,\n implementation=self._implementation,\n )\n\n def _with_binary(self, op: Callable[..., Column], other: Self | Any) -> Self:\n return self.__class__(\n self._callable_to_eval_series(op, other=other),\n self._push_down_window_function(op, other=other),\n evaluate_output_names=self._evaluate_output_names,\n alias_output_names=self._alias_output_names,\n backend_version=self._backend_version,\n version=self._version,\n implementation=self._implementation,\n )\n\n def _with_alias_output_names(self, func: AliasNames | None, /) -> Self:\n return type(self)(\n self._call,\n self._window_function,\n evaluate_output_names=self._evaluate_output_names,\n alias_output_names=func,\n backend_version=self._backend_version,\n version=self._version,\n implementation=self._implementation,\n )\n\n def __truediv__(self, other: SparkLikeExpr) -> Self:\n def _truediv(expr: Column, other: Column) -> Column:\n return true_divide(self._F, expr, other)\n\n return self._with_binary(_truediv, other)\n\n def __rtruediv__(self, other: SparkLikeExpr) -> Self:\n def _rtruediv(expr: Column, other: Column) -> Column:\n return true_divide(self._F, other, expr)\n\n return self._with_binary(_rtruediv, other).alias("literal")\n\n def __floordiv__(self, other: SparkLikeExpr) -> Self:\n def _floordiv(expr: Column, other: Column) -> Column:\n return self._F.floor(true_divide(self._F, expr, other))\n\n return self._with_binary(_floordiv, other)\n\n def __rfloordiv__(self, other: SparkLikeExpr) -> Self:\n def _rfloordiv(expr: Column, other: Column) -> Column:\n return self._F.floor(true_divide(self._F, other, expr))\n\n return self._with_binary(_rfloordiv, other).alias("literal")\n\n def __invert__(self) -> Self:\n invert = cast("Callable[..., Column]", operator.invert)\n return self._with_elementwise(invert)\n\n def abs(self) -> Self:\n return self._with_elementwise(self._F.abs)\n\n def all(self) -> Self:\n def f(expr: Column) -> Column:\n return self._F.coalesce(self._F.bool_and(expr), self._F.lit(True)) # noqa: FBT003\n\n def window_f(\n df: SparkLikeLazyFrame, window_inputs: SparkWindowInputs\n ) -> Sequence[Column]:\n return [\n self._F.coalesce(\n self._F.bool_and(expr).over(\n self.partition_by(*window_inputs.partition_by)\n ),\n self._F.lit(True), # noqa: FBT003\n )\n for expr in self(df)\n ]\n\n return self._with_callable(f)._with_window_function(window_f)\n\n def any(self) -> Self:\n def f(expr: Column) -> Column:\n return self._F.coalesce(self._F.bool_or(expr), self._F.lit(False)) # noqa: FBT003\n\n def window_f(\n df: SparkLikeLazyFrame, window_inputs: SparkWindowInputs\n ) -> Sequence[Column]:\n return [\n self._F.coalesce(\n self._F.bool_or(expr).over(\n self.partition_by(*window_inputs.partition_by)\n ),\n self._F.lit(False), # noqa: FBT003\n )\n for expr in self(df)\n ]\n\n return self._with_callable(f)._with_window_function(window_f)\n\n def cast(self, dtype: IntoDType) -> Self:\n def _cast(expr: Column) -> Column:\n spark_dtype = narwhals_to_native_dtype(\n dtype, self._version, self._native_dtypes\n )\n return expr.cast(spark_dtype)\n\n return self._with_elementwise(_cast)\n\n def count(self) -> Self:\n return self._with_callable(self._F.count)\n\n def max(self) -> Self:\n return self._with_callable(self._F.max)\n\n def mean(self) -> Self:\n return self._with_callable(self._F.mean)\n\n def median(self) -> Self:\n def _median(expr: Column) -> Column:\n if (\n self._implementation\n in {Implementation.PYSPARK, Implementation.PYSPARK_CONNECT}\n and (pyspark := get_pyspark()) is not None\n and parse_version(pyspark) < (3, 4)\n ): # pragma: no cover\n # Use percentile_approx with default accuracy parameter (10000)\n return self._F.percentile_approx(expr.cast("double"), 0.5)\n\n return self._F.median(expr)\n\n return self._with_callable(_median)\n\n def min(self) -> Self:\n return self._with_callable(self._F.min)\n\n def null_count(self) -> Self:\n def _null_count(expr: Column) -> Column:\n return self._F.count_if(self._F.isnull(expr))\n\n return self._with_callable(_null_count)\n\n def sum(self) -> Self:\n def f(expr: Column) -> Column:\n return self._F.coalesce(self._F.sum(expr), self._F.lit(0))\n\n def window_f(\n df: SparkLikeLazyFrame, window_inputs: SparkWindowInputs\n ) -> Sequence[Column]:\n return [\n self._F.coalesce(\n self._F.sum(expr).over(\n self.partition_by(*window_inputs.partition_by)\n ),\n self._F.lit(0),\n )\n for expr in self(df)\n ]\n\n return self._with_callable(f)._with_window_function(window_f)\n\n def std(self, ddof: int) -> Self:\n F = self._F # noqa: N806\n if ddof == 0:\n return self._with_callable(F.stddev_pop)\n if ddof == 1:\n return self._with_callable(F.stddev_samp)\n\n def func(expr: Column) -> Column:\n n_rows = F.count(expr)\n return F.stddev_samp(expr) * F.sqrt((n_rows - 1) / (n_rows - ddof))\n\n return self._with_callable(func)\n\n def var(self, ddof: int) -> Self:\n F = self._F # noqa: N806\n if ddof == 0:\n return self._with_callable(F.var_pop)\n if ddof == 1:\n return self._with_callable(F.var_samp)\n\n def func(expr: Column) -> Column:\n n_rows = F.count(expr)\n return F.var_samp(expr) * (n_rows - 1) / (n_rows - ddof)\n\n return self._with_callable(func)\n\n def clip(\n self,\n lower_bound: Self | NumericLiteral | TemporalLiteral | None = None,\n upper_bound: Self | NumericLiteral | TemporalLiteral | None = None,\n ) -> Self:\n def _clip_lower(expr: Column, lower_bound: Column) -> Column:\n result = expr\n return self._F.when(result < lower_bound, lower_bound).otherwise(result)\n\n def _clip_upper(expr: Column, upper_bound: Column) -> Column:\n result = expr\n return self._F.when(result > upper_bound, upper_bound).otherwise(result)\n\n def _clip_both(expr: Column, lower_bound: Column, upper_bound: Column) -> Column:\n return (\n self._F.when(expr < lower_bound, lower_bound)\n .when(expr > upper_bound, upper_bound)\n .otherwise(expr)\n )\n\n if lower_bound is None:\n return self._with_elementwise(_clip_upper, upper_bound=upper_bound)\n if upper_bound is None:\n return self._with_elementwise(_clip_lower, lower_bound=lower_bound)\n return self._with_elementwise(\n _clip_both, lower_bound=lower_bound, upper_bound=upper_bound\n )\n\n def is_finite(self) -> Self:\n def _is_finite(expr: Column) -> Column:\n # A value is finite if it's not NaN, and not infinite, while NULLs should be\n # preserved\n is_finite_condition = (\n ~self._F.isnan(expr)\n & (expr != self._F.lit(float("inf")))\n & (expr != self._F.lit(float("-inf")))\n )\n return self._F.when(~self._F.isnull(expr), is_finite_condition).otherwise(\n None\n )\n\n return self._with_elementwise(_is_finite)\n\n def is_in(self, values: Sequence[Any]) -> Self:\n def _is_in(expr: Column) -> Column:\n return expr.isin(values) if values else self._F.lit(False) # noqa: FBT003\n\n return self._with_elementwise(_is_in)\n\n def is_unique(self) -> Self:\n def _is_unique(expr: Column, *partition_by: str | Column) -> Column:\n return self._F.count("*").over(self.partition_by(expr, *partition_by)) == 1\n\n def _unpartitioned_is_unique(expr: Column) -> Column:\n return _is_unique(expr)\n\n def _partitioned_is_unique(\n df: SparkLikeLazyFrame, inputs: SparkWindowInputs\n ) -> Sequence[Column]:\n assert not inputs.order_by # noqa: S101\n return [_is_unique(expr, *inputs.partition_by) for expr in self(df)]\n\n return self._with_callable(_unpartitioned_is_unique)._with_window_function(\n _partitioned_is_unique\n )\n\n def len(self) -> Self:\n def _len(_expr: Column) -> Column:\n # Use count(*) to count all rows including nulls\n return self._F.count("*")\n\n return self._with_callable(_len)\n\n def round(self, decimals: int) -> Self:\n def _round(expr: Column) -> Column:\n return self._F.round(expr, decimals)\n\n return self._with_elementwise(_round)\n\n def skew(self) -> Self:\n return self._with_callable(self._F.skewness)\n\n def kurtosis(self) -> Self:\n return self._with_callable(self._F.kurtosis)\n\n def n_unique(self) -> Self:\n def _n_unique(expr: Column) -> Column:\n return self._F.count_distinct(expr) + self._F.max(\n self._F.isnull(expr).cast(self._native_dtypes.IntegerType())\n )\n\n return self._with_callable(_n_unique)\n\n def over(self, partition_by: Sequence[str | Column], order_by: Sequence[str]) -> Self:\n def func(df: SparkLikeLazyFrame) -> Sequence[Column]:\n return self.window_function(df, WindowInputs(partition_by, order_by))\n\n return self.__class__(\n func,\n evaluate_output_names=self._evaluate_output_names,\n alias_output_names=self._alias_output_names,\n backend_version=self._backend_version,\n version=self._version,\n implementation=self._implementation,\n )\n\n def is_null(self) -> Self:\n return self._with_elementwise(self._F.isnull)\n\n def is_nan(self) -> Self:\n def _is_nan(expr: Column) -> Column:\n return self._F.when(self._F.isnull(expr), None).otherwise(self._F.isnan(expr))\n\n return self._with_elementwise(_is_nan)\n\n def shift(self, n: int) -> Self:\n def func(df: SparkLikeLazyFrame, inputs: SparkWindowInputs) -> Sequence[Column]:\n window = self.partition_by(*inputs.partition_by).orderBy(\n *self._sort(*inputs.order_by)\n )\n return [self._F.lag(expr, n).over(window) for expr in self(df)]\n\n return self._with_window_function(func)\n\n def is_first_distinct(self) -> Self:\n def func(df: SparkLikeLazyFrame, inputs: SparkWindowInputs) -> Sequence[Column]:\n return [\n self._F.row_number().over(\n self.partition_by(*inputs.partition_by, expr).orderBy(\n *self._sort(*inputs.order_by)\n )\n )\n == 1\n for expr in self(df)\n ]\n\n return self._with_window_function(func)\n\n def is_last_distinct(self) -> Self:\n def func(df: SparkLikeLazyFrame, inputs: SparkWindowInputs) -> Sequence[Column]:\n return [\n self._F.row_number().over(\n self.partition_by(*inputs.partition_by, expr).orderBy(\n *self._sort(*inputs.order_by, descending=True, nulls_last=True)\n )\n )\n == 1\n for expr in self(df)\n ]\n\n return self._with_window_function(func)\n\n def diff(self) -> Self:\n def func(df: SparkLikeLazyFrame, inputs: SparkWindowInputs) -> Sequence[Column]:\n window = self.partition_by(*inputs.partition_by).orderBy(\n *self._sort(*inputs.order_by)\n )\n return [expr - self._F.lag(expr).over(window) for expr in self(df)]\n\n return self._with_window_function(func)\n\n def cum_sum(self, *, reverse: bool) -> Self:\n return self._with_window_function(\n self._cum_window_func(reverse=reverse, func_name="sum")\n )\n\n def cum_max(self, *, reverse: bool) -> Self:\n return self._with_window_function(\n self._cum_window_func(reverse=reverse, func_name="max")\n )\n\n def cum_min(self, *, reverse: bool) -> Self:\n return self._with_window_function(\n self._cum_window_func(reverse=reverse, func_name="min")\n )\n\n def cum_count(self, *, reverse: bool) -> Self:\n return self._with_window_function(\n self._cum_window_func(reverse=reverse, func_name="count")\n )\n\n def cum_prod(self, *, reverse: bool) -> Self:\n return self._with_window_function(\n self._cum_window_func(reverse=reverse, func_name="product")\n )\n\n def fill_null(\n self,\n value: Self | NonNestedLiteral,\n strategy: FillNullStrategy | None,\n limit: int | None,\n ) -> Self:\n if strategy is not None:\n\n def _fill_with_strategy(\n df: SparkLikeLazyFrame, inputs: SparkWindowInputs\n ) -> Sequence[Column]:\n fn = self._F.last_value if strategy == "forward" else self._F.first_value\n if strategy == "forward":\n start = self._Window.unboundedPreceding if limit is None else -limit\n end = self._Window.currentRow\n else:\n start = self._Window.currentRow\n end = self._Window.unboundedFollowing if limit is None else limit\n return [\n fn(expr, ignoreNulls=True).over(\n self.partition_by(*inputs.partition_by)\n .orderBy(*self._sort(*inputs.order_by))\n .rowsBetween(start, end)\n )\n for expr in self(df)\n ]\n\n return self._with_window_function(_fill_with_strategy)\n\n def _fill_constant(expr: Column, value: Column) -> Column:\n return self._F.ifnull(expr, value)\n\n return self._with_elementwise(_fill_constant, value=value)\n\n def rolling_sum(self, window_size: int, *, min_samples: int, center: bool) -> Self:\n return self._with_window_function(\n self._rolling_window_func(\n func_name="sum",\n center=center,\n window_size=window_size,\n min_samples=min_samples,\n )\n )\n\n def rolling_mean(self, window_size: int, *, min_samples: int, center: bool) -> Self:\n return self._with_window_function(\n self._rolling_window_func(\n func_name="mean",\n center=center,\n window_size=window_size,\n min_samples=min_samples,\n )\n )\n\n def rolling_var(\n self, window_size: int, *, min_samples: int, center: bool, ddof: int\n ) -> Self:\n return self._with_window_function(\n self._rolling_window_func(\n func_name="var",\n center=center,\n window_size=window_size,\n min_samples=min_samples,\n ddof=ddof,\n )\n )\n\n def rolling_std(\n self, window_size: int, *, min_samples: int, center: bool, ddof: int\n ) -> Self:\n return self._with_window_function(\n self._rolling_window_func(\n func_name="std",\n center=center,\n window_size=window_size,\n min_samples=min_samples,\n ddof=ddof,\n )\n )\n\n def rank(self, method: RankMethod, *, descending: bool) -> Self:\n func_name = self._REMAP_RANK_METHOD[method]\n\n def _rank(\n expr: Column,\n *,\n descending: bool,\n partition_by: Sequence[str | Column] | None = None,\n ) -> Column:\n order_by = self._sort(expr, descending=descending, nulls_last=True)\n if partition_by is not None:\n window = self.partition_by(*partition_by).orderBy(*order_by)\n count_window = self.partition_by(*partition_by, expr)\n else:\n window = self.partition_by().orderBy(*order_by)\n count_window = self.partition_by(expr)\n if method == "max":\n rank_expr = (\n getattr(self._F, func_name)().over(window)\n + self._F.count(expr).over(count_window)\n - self._F.lit(1)\n )\n\n elif method == "average":\n rank_expr = getattr(self._F, func_name)().over(window) + (\n self._F.count(expr).over(count_window) - self._F.lit(1)\n ) / self._F.lit(2)\n\n else:\n rank_expr = getattr(self._F, func_name)().over(window)\n\n return self._F.when(expr.isNotNull(), rank_expr)\n\n def _unpartitioned_rank(expr: Column) -> Column:\n return _rank(expr, descending=descending)\n\n def _partitioned_rank(\n df: SparkLikeLazyFrame, inputs: SparkWindowInputs\n ) -> Sequence[Column]:\n assert not inputs.order_by # noqa: S101\n return [\n _rank(expr, descending=descending, partition_by=inputs.partition_by)\n for expr in self(df)\n ]\n\n return self._with_callable(_unpartitioned_rank)._with_window_function(\n _partitioned_rank\n )\n\n def log(self, base: float) -> Self:\n def _log(expr: Column) -> Column:\n return (\n self._F.when(expr < 0, self._F.lit(float("nan")))\n .when(expr == 0, self._F.lit(float("-inf")))\n .otherwise(self._F.log(float(base), expr))\n )\n\n return self._with_elementwise(_log)\n\n def exp(self) -> Self:\n def _exp(expr: Column) -> Column:\n return self._F.exp(expr)\n\n return self._with_elementwise(_exp)\n\n def sqrt(self) -> Self:\n def _sqrt(expr: Column) -> Column:\n return self._F.when(expr < 0, self._F.lit(float("nan"))).otherwise(\n self._F.sqrt(expr)\n )\n\n return self._with_elementwise(_sqrt)\n\n @property\n def str(self) -> SparkLikeExprStringNamespace:\n return SparkLikeExprStringNamespace(self)\n\n @property\n def dt(self) -> SparkLikeExprDateTimeNamespace:\n return SparkLikeExprDateTimeNamespace(self)\n\n @property\n def list(self) -> SparkLikeExprListNamespace:\n return SparkLikeExprListNamespace(self)\n\n @property\n def struct(self) -> SparkLikeExprStructNamespace:\n return SparkLikeExprStructNamespace(self)\n\n drop_nulls = not_implemented()\n unique = not_implemented()\n quantile = not_implemented()\n | .venv\Lib\site-packages\narwhals\_spark_like\expr.py | expr.py | Python | 33,165 | 0.95 | 0.2 | 0.026076 | python-kit | 678 | 2023-08-08T11:09:18.577094 | BSD-3-Clause | false | 9455823c95df56827a42ad228f27cd63 |
from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom narwhals._compliant.any_namespace import DateTimeNamespace\nfrom narwhals._compliant.expr import LazyExprNamespace\nfrom narwhals._constants import US_PER_SECOND\nfrom narwhals._duration import parse_interval_string\nfrom narwhals._spark_like.utils import (\n UNITS_DICT,\n fetch_session_time_zone,\n strptime_to_pyspark_format,\n)\nfrom narwhals._utils import not_implemented\n\nif TYPE_CHECKING:\n from collections.abc import Sequence\n\n from sqlframe.base.column import Column\n\n from narwhals._spark_like.dataframe import SparkLikeLazyFrame\n from narwhals._spark_like.expr import SparkLikeExpr\n\n\nclass SparkLikeExprDateTimeNamespace(\n LazyExprNamespace["SparkLikeExpr"], DateTimeNamespace["SparkLikeExpr"]\n):\n def to_string(self, format: str) -> SparkLikeExpr:\n F = self.compliant._F # noqa: N806\n\n def _to_string(_input: Column) -> Column:\n # Handle special formats\n if format == "%G-W%V":\n return self._format_iso_week(_input)\n if format == "%G-W%V-%u":\n return self._format_iso_week_with_day(_input)\n\n format_, suffix = self._format_microseconds(_input, format)\n\n # Convert Python format to PySpark format\n pyspark_fmt = strptime_to_pyspark_format(format_)\n\n result = F.date_format(_input, pyspark_fmt)\n if "T" in format_:\n # `strptime_to_pyspark_format` replaces "T" with " " since pyspark\n # does not support the literal "T" in `date_format`.\n # If no other spaces are in the given format, then we can revert this\n # operation, otherwise we raise an exception.\n if " " not in format_:\n result = F.replace(result, F.lit(" "), F.lit("T"))\n else: # pragma: no cover\n msg = (\n "`dt.to_string` with a format that contains both spaces and "\n " the literal 'T' is not supported for spark-like backends."\n )\n raise NotImplementedError(msg)\n\n return F.concat(result, *suffix)\n\n return self.compliant._with_callable(_to_string)\n\n def date(self) -> SparkLikeExpr:\n return self.compliant._with_callable(self.compliant._F.to_date)\n\n def year(self) -> SparkLikeExpr:\n return self.compliant._with_callable(self.compliant._F.year)\n\n def month(self) -> SparkLikeExpr:\n return self.compliant._with_callable(self.compliant._F.month)\n\n def day(self) -> SparkLikeExpr:\n return self.compliant._with_callable(self.compliant._F.day)\n\n def hour(self) -> SparkLikeExpr:\n return self.compliant._with_callable(self.compliant._F.hour)\n\n def minute(self) -> SparkLikeExpr:\n return self.compliant._with_callable(self.compliant._F.minute)\n\n def second(self) -> SparkLikeExpr:\n return self.compliant._with_callable(self.compliant._F.second)\n\n def millisecond(self) -> SparkLikeExpr:\n def _millisecond(expr: Column) -> Column:\n return self.compliant._F.floor(\n (self.compliant._F.unix_micros(expr) % US_PER_SECOND) / 1000\n )\n\n return self.compliant._with_callable(_millisecond)\n\n def microsecond(self) -> SparkLikeExpr:\n def _microsecond(expr: Column) -> Column:\n return self.compliant._F.unix_micros(expr) % US_PER_SECOND\n\n return self.compliant._with_callable(_microsecond)\n\n def nanosecond(self) -> SparkLikeExpr:\n def _nanosecond(expr: Column) -> Column:\n return (self.compliant._F.unix_micros(expr) % US_PER_SECOND) * 1000\n\n return self.compliant._with_callable(_nanosecond)\n\n def ordinal_day(self) -> SparkLikeExpr:\n return self.compliant._with_callable(self.compliant._F.dayofyear)\n\n def weekday(self) -> SparkLikeExpr:\n def _weekday(expr: Column) -> Column:\n # PySpark's dayofweek returns 1-7 for Sunday-Saturday\n return (self.compliant._F.dayofweek(expr) + 6) % 7\n\n return self.compliant._with_callable(_weekday)\n\n def truncate(self, every: str) -> SparkLikeExpr:\n multiple, unit = parse_interval_string(every)\n if multiple != 1:\n msg = f"Only multiple 1 is currently supported for Spark-like.\nGot {multiple!s}."\n raise ValueError(msg)\n if unit == "ns":\n msg = "Truncating to nanoseconds is not yet supported for Spark-like."\n raise NotImplementedError(msg)\n format = UNITS_DICT[unit]\n\n def _truncate(expr: Column) -> Column:\n return self.compliant._F.date_trunc(format, expr)\n\n return self.compliant._with_callable(_truncate)\n\n def _no_op_time_zone(self, time_zone: str) -> SparkLikeExpr: # pragma: no cover\n def func(df: SparkLikeLazyFrame) -> Sequence[Column]:\n native_series_list = self.compliant(df)\n conn_time_zone = fetch_session_time_zone(df.native.sparkSession)\n if conn_time_zone != time_zone:\n msg = (\n "PySpark stores the time zone in the session, rather than in the "\n f"data type, so changing the timezone to anything other than {conn_time_zone} "\n " (the current session time zone) is not supported."\n )\n raise NotImplementedError(msg)\n return native_series_list\n\n return self.compliant.__class__(\n func,\n evaluate_output_names=self.compliant._evaluate_output_names,\n alias_output_names=self.compliant._alias_output_names,\n backend_version=self.compliant._backend_version,\n version=self.compliant._version,\n implementation=self.compliant._implementation,\n )\n\n def convert_time_zone(self, time_zone: str) -> SparkLikeExpr: # pragma: no cover\n return self._no_op_time_zone(time_zone)\n\n def replace_time_zone(\n self, time_zone: str | None\n ) -> SparkLikeExpr: # pragma: no cover\n if time_zone is None:\n return self.compliant._with_callable(\n lambda _input: _input.cast("timestamp_ntz")\n )\n else:\n return self._no_op_time_zone(time_zone)\n\n def _format_iso_week_with_day(self, _input: Column) -> Column:\n """Format datetime as ISO week string with day."""\n F = self.compliant._F # noqa: N806\n\n year = F.date_format(_input, "yyyy")\n week = F.lpad(F.weekofyear(_input).cast("string"), 2, "0")\n day = F.dayofweek(_input)\n # Adjust Sunday from 1 to 7\n day = F.when(day == 1, 7).otherwise(day - 1)\n return F.concat(year, F.lit("-W"), week, F.lit("-"), day.cast("string"))\n\n def _format_iso_week(self, _input: Column) -> Column:\n """Format datetime as ISO week string."""\n F = self.compliant._F # noqa: N806\n\n year = F.date_format(_input, "yyyy")\n week = F.lpad(F.weekofyear(_input).cast("string"), 2, "0")\n return F.concat(year, F.lit("-W"), week)\n\n def _format_microseconds(\n self, _input: Column, format: str\n ) -> tuple[str, tuple[Column, ...]]:\n """Format microseconds if present in format, else it's a no-op."""\n F = self.compliant._F # noqa: N806\n\n suffix: tuple[Column, ...]\n if format.endswith((".%f", "%.f")):\n import re\n\n micros = F.unix_micros(_input) % US_PER_SECOND\n micros_str = F.lpad(micros.cast("string"), 6, "0")\n suffix = (F.lit("."), micros_str)\n format_ = re.sub(r"(.%|%.)f$", "", format)\n return format_, suffix\n\n return format, ()\n\n timestamp = not_implemented()\n total_seconds = not_implemented()\n total_minutes = not_implemented()\n total_milliseconds = not_implemented()\n total_microseconds = not_implemented()\n total_nanoseconds = not_implemented()\n | .venv\Lib\site-packages\narwhals\_spark_like\expr_dt.py | expr_dt.py | Python | 8,002 | 0.95 | 0.209756 | 0.05 | awesome-app | 910 | 2025-05-10T07:05:35.746639 | GPL-3.0 | false | 4fbee5e2816642c99d546da0c2f53f2f |
from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom narwhals._compliant.any_namespace import ListNamespace\nfrom narwhals._compliant.expr import LazyExprNamespace\n\nif TYPE_CHECKING:\n from narwhals._spark_like.expr import SparkLikeExpr\n\n\nclass SparkLikeExprListNamespace(\n LazyExprNamespace["SparkLikeExpr"], ListNamespace["SparkLikeExpr"]\n):\n def len(self) -> SparkLikeExpr:\n return self.compliant._with_callable(self.compliant._F.array_size)\n | .venv\Lib\site-packages\narwhals\_spark_like\expr_list.py | expr_list.py | Python | 481 | 0.85 | 0.1875 | 0 | node-utils | 546 | 2024-02-24T08:34:57.741722 | Apache-2.0 | false | a4a1c6b01e27f1a68c875e22e5b28ce2 |
from __future__ import annotations\n\nfrom functools import partial\nfrom typing import TYPE_CHECKING\n\nfrom narwhals._compliant.any_namespace import StringNamespace\nfrom narwhals._compliant.expr import LazyExprNamespace\nfrom narwhals._spark_like.utils import strptime_to_pyspark_format\nfrom narwhals._utils import _is_naive_format, not_implemented\n\nif TYPE_CHECKING:\n from sqlframe.base.column import Column\n\n from narwhals._spark_like.expr import SparkLikeExpr\n\n\nclass SparkLikeExprStringNamespace(\n LazyExprNamespace["SparkLikeExpr"], StringNamespace["SparkLikeExpr"]\n):\n def len_chars(self) -> SparkLikeExpr:\n return self.compliant._with_callable(self.compliant._F.char_length)\n\n def replace_all(self, pattern: str, value: str, *, literal: bool) -> SparkLikeExpr:\n def func(expr: Column) -> Column:\n replace_all_func = (\n self.compliant._F.replace if literal else self.compliant._F.regexp_replace\n )\n return replace_all_func(\n expr,\n self.compliant._F.lit(pattern), # pyright: ignore[reportArgumentType]\n self.compliant._F.lit(value), # pyright: ignore[reportArgumentType]\n )\n\n return self.compliant._with_callable(func)\n\n def strip_chars(self, characters: str | None) -> SparkLikeExpr:\n import string\n\n def func(expr: Column) -> Column:\n to_remove = characters if characters is not None else string.whitespace\n return self.compliant._F.btrim(expr, self.compliant._F.lit(to_remove))\n\n return self.compliant._with_callable(func)\n\n def starts_with(self, prefix: str) -> SparkLikeExpr:\n return self.compliant._with_callable(\n lambda expr: self.compliant._F.startswith(expr, self.compliant._F.lit(prefix))\n )\n\n def ends_with(self, suffix: str) -> SparkLikeExpr:\n return self.compliant._with_callable(\n lambda expr: self.compliant._F.endswith(expr, self.compliant._F.lit(suffix))\n )\n\n def contains(self, pattern: str, *, literal: bool) -> SparkLikeExpr:\n def func(expr: Column) -> Column:\n contains_func = (\n self.compliant._F.contains if literal else self.compliant._F.regexp\n )\n return contains_func(expr, self.compliant._F.lit(pattern))\n\n return self.compliant._with_callable(func)\n\n def slice(self, offset: int, length: int | None) -> SparkLikeExpr:\n # From the docs: https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.substring.html\n # The position is not zero based, but 1 based index.\n def func(expr: Column) -> Column:\n col_length = self.compliant._F.char_length(expr)\n\n _offset = (\n col_length + self.compliant._F.lit(offset + 1)\n if offset < 0\n else self.compliant._F.lit(offset + 1)\n )\n _length = self.compliant._F.lit(length) if length is not None else col_length\n return expr.substr(_offset, _length)\n\n return self.compliant._with_callable(func)\n\n def split(self, by: str) -> SparkLikeExpr:\n return self.compliant._with_callable(\n lambda expr: self.compliant._F.split(expr, by)\n )\n\n def to_uppercase(self) -> SparkLikeExpr:\n return self.compliant._with_callable(self.compliant._F.upper)\n\n def to_lowercase(self) -> SparkLikeExpr:\n return self.compliant._with_callable(self.compliant._F.lower)\n\n def to_datetime(self, format: str | None) -> SparkLikeExpr:\n F = self.compliant._F # noqa: N806\n if not format:\n function = F.to_timestamp\n elif _is_naive_format(format):\n function = partial(\n F.to_timestamp_ntz, format=F.lit(strptime_to_pyspark_format(format))\n )\n else:\n format = strptime_to_pyspark_format(format)\n function = partial(F.to_timestamp, format=format)\n return self.compliant._with_callable(\n lambda expr: function(F.replace(expr, F.lit("T"), F.lit(" ")))\n )\n\n def to_date(self, format: str | None) -> SparkLikeExpr:\n F = self._compliant_expr._F # noqa: N806\n return self._compliant_expr._with_callable(\n lambda expr: F.to_date(expr, format=strptime_to_pyspark_format(format))\n )\n\n def zfill(self, width: int) -> SparkLikeExpr:\n def func(expr: Column) -> Column:\n F = self.compliant._F # noqa: N806\n\n length = F.length(expr)\n less_than_width = length < width\n hyphen, plus = F.lit("-"), F.lit("+")\n starts_with_minus = F.startswith(expr, hyphen)\n starts_with_plus = F.startswith(expr, plus)\n sub_length = length - F.lit(1)\n # NOTE: `len` annotated as `int`, but `Column.substr` accepts `int | Column`\n substring = F.substring(expr, 2, sub_length) # pyright: ignore[reportArgumentType]\n padded_substring = F.lpad(substring, width - 1, "0")\n return (\n F.when(\n starts_with_minus & less_than_width,\n F.concat(hyphen, padded_substring),\n )\n .when(\n starts_with_plus & less_than_width, F.concat(plus, padded_substring)\n )\n .when(less_than_width, F.lpad(expr, width, "0"))\n .otherwise(expr)\n )\n\n return self.compliant._with_callable(func)\n\n replace = not_implemented()\n | .venv\Lib\site-packages\narwhals\_spark_like\expr_str.py | expr_str.py | Python | 5,578 | 0.95 | 0.215827 | 0.026786 | awesome-app | 771 | 2024-07-06T18:07:28.287923 | Apache-2.0 | false | a95307357849a47cfecb6403c1a8787a |
from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom narwhals._compliant.any_namespace import StructNamespace\nfrom narwhals._compliant.expr import LazyExprNamespace\n\nif TYPE_CHECKING:\n from sqlframe.base.column import Column\n\n from narwhals._spark_like.expr import SparkLikeExpr\n\n\nclass SparkLikeExprStructNamespace(\n LazyExprNamespace["SparkLikeExpr"], StructNamespace["SparkLikeExpr"]\n):\n def field(self, name: str) -> SparkLikeExpr:\n def func(expr: Column) -> Column:\n return expr.getField(name)\n\n return self.compliant._with_callable(func).alias(name)\n | .venv\Lib\site-packages\narwhals\_spark_like\expr_struct.py | expr_struct.py | Python | 615 | 0.85 | 0.190476 | 0 | awesome-app | 153 | 2025-06-19T20:03:16.950942 | GPL-3.0 | false | adda4408971e5ebdb2300611883bfc12 |
from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom narwhals._compliant import LazyGroupBy\n\nif TYPE_CHECKING:\n from collections.abc import Sequence\n\n from sqlframe.base.column import Column # noqa: F401\n\n from narwhals._spark_like.dataframe import SparkLikeLazyFrame\n from narwhals._spark_like.expr import SparkLikeExpr\n\n\nclass SparkLikeLazyGroupBy(LazyGroupBy["SparkLikeLazyFrame", "SparkLikeExpr", "Column"]):\n def __init__(\n self,\n df: SparkLikeLazyFrame,\n keys: Sequence[SparkLikeExpr] | Sequence[str],\n /,\n *,\n drop_null_keys: bool,\n ) -> None:\n frame, self._keys, self._output_key_names = self._parse_keys(df, keys=keys)\n self._compliant_frame = frame.drop_nulls(self._keys) if drop_null_keys else frame\n\n def agg(self, *exprs: SparkLikeExpr) -> SparkLikeLazyFrame:\n result = (\n self.compliant.native.groupBy(*self._keys).agg(*agg_columns)\n if (agg_columns := list(self._evaluate_exprs(exprs)))\n else self.compliant.native.select(*self._keys).dropDuplicates()\n )\n\n return self.compliant._with_native(result).rename(\n dict(zip(self._keys, self._output_key_names))\n )\n | .venv\Lib\site-packages\narwhals\_spark_like\group_by.py | group_by.py | Python | 1,245 | 0.95 | 0.162162 | 0.035714 | vue-tools | 251 | 2025-01-28T15:43:50.118396 | GPL-3.0 | false | 7e5128b0540bbeb45d8c9c1a04a312b6 |
from __future__ import annotations\n\nimport operator\nfrom functools import reduce\nfrom typing import TYPE_CHECKING\n\nfrom narwhals._compliant import LazyNamespace, LazyThen, LazyWhen\nfrom narwhals._expression_parsing import (\n combine_alias_output_names,\n combine_evaluate_output_names,\n)\nfrom narwhals._spark_like.dataframe import SparkLikeLazyFrame\nfrom narwhals._spark_like.expr import SparkLikeExpr\nfrom narwhals._spark_like.selectors import SparkLikeSelectorNamespace\nfrom narwhals._spark_like.utils import (\n import_functions,\n import_native_dtypes,\n narwhals_to_native_dtype,\n true_divide,\n)\n\nif TYPE_CHECKING:\n from collections.abc import Iterable, Sequence\n\n from sqlframe.base.column import Column\n\n from narwhals._spark_like.dataframe import SQLFrameDataFrame # noqa: F401\n from narwhals._spark_like.expr import SparkWindowInputs\n from narwhals._utils import Implementation, Version\n from narwhals.typing import ConcatMethod, IntoDType, NonNestedLiteral\n\n\nclass SparkLikeNamespace(\n LazyNamespace[SparkLikeLazyFrame, SparkLikeExpr, "SQLFrameDataFrame"]\n):\n def __init__(\n self,\n *,\n backend_version: tuple[int, ...],\n version: Version,\n implementation: Implementation,\n ) -> None:\n self._backend_version = backend_version\n self._version = version\n self._implementation = implementation\n\n @property\n def selectors(self) -> SparkLikeSelectorNamespace:\n return SparkLikeSelectorNamespace.from_namespace(self)\n\n @property\n def _expr(self) -> type[SparkLikeExpr]:\n return SparkLikeExpr\n\n @property\n def _lazyframe(self) -> type[SparkLikeLazyFrame]:\n return SparkLikeLazyFrame\n\n @property\n def _F(self): # type: ignore[no-untyped-def] # noqa: ANN202, N802\n if TYPE_CHECKING:\n from sqlframe.base import functions\n\n return functions\n else:\n return import_functions(self._implementation)\n\n @property\n def _native_dtypes(self): # type: ignore[no-untyped-def] # noqa: ANN202\n if TYPE_CHECKING:\n from sqlframe.base import types\n\n return types\n else:\n return import_native_dtypes(self._implementation)\n\n def lit(self, value: NonNestedLiteral, dtype: IntoDType | None) -> SparkLikeExpr:\n def _lit(df: SparkLikeLazyFrame) -> list[Column]:\n column = df._F.lit(value)\n if dtype:\n native_dtype = narwhals_to_native_dtype(\n dtype, version=self._version, spark_types=df._native_dtypes\n )\n column = column.cast(native_dtype)\n\n return [column]\n\n return self._expr(\n call=_lit,\n evaluate_output_names=lambda _df: ["literal"],\n alias_output_names=None,\n backend_version=self._backend_version,\n version=self._version,\n implementation=self._implementation,\n )\n\n def len(self) -> SparkLikeExpr:\n def func(df: SparkLikeLazyFrame) -> list[Column]:\n return [df._F.count("*")]\n\n return self._expr(\n func,\n evaluate_output_names=lambda _df: ["len"],\n alias_output_names=None,\n backend_version=self._backend_version,\n version=self._version,\n implementation=self._implementation,\n )\n\n def all_horizontal(self, *exprs: SparkLikeExpr, ignore_nulls: bool) -> SparkLikeExpr:\n def func(cols: Iterable[Column]) -> Column:\n it = (\n (self._F.coalesce(col, self._F.lit(True)) for col in cols) # noqa: FBT003\n if ignore_nulls\n else cols\n )\n return reduce(operator.and_, it)\n\n return self._expr._from_elementwise_horizontal_op(func, *exprs)\n\n def any_horizontal(self, *exprs: SparkLikeExpr, ignore_nulls: bool) -> SparkLikeExpr:\n def func(cols: Iterable[Column]) -> Column:\n it = (\n (self._F.coalesce(col, self._F.lit(False)) for col in cols) # noqa: FBT003\n if ignore_nulls\n else cols\n )\n return reduce(operator.or_, it)\n\n return self._expr._from_elementwise_horizontal_op(func, *exprs)\n\n def max_horizontal(self, *exprs: SparkLikeExpr) -> SparkLikeExpr:\n def func(cols: Iterable[Column]) -> Column:\n return self._F.greatest(*cols)\n\n return self._expr._from_elementwise_horizontal_op(func, *exprs)\n\n def min_horizontal(self, *exprs: SparkLikeExpr) -> SparkLikeExpr:\n def func(cols: Iterable[Column]) -> Column:\n return self._F.least(*cols)\n\n return self._expr._from_elementwise_horizontal_op(func, *exprs)\n\n def sum_horizontal(self, *exprs: SparkLikeExpr) -> SparkLikeExpr:\n def func(cols: Iterable[Column]) -> Column:\n return reduce(\n operator.add, (self._F.coalesce(col, self._F.lit(0)) for col in cols)\n )\n\n return self._expr._from_elementwise_horizontal_op(func, *exprs)\n\n def mean_horizontal(self, *exprs: SparkLikeExpr) -> SparkLikeExpr:\n def func(cols: Iterable[Column]) -> Column:\n cols = list(cols)\n F = exprs[0]._F # noqa: N806\n numerator = reduce(\n operator.add, (self._F.coalesce(col, self._F.lit(0)) for col in cols)\n )\n denominator = reduce(\n operator.add,\n (col.isNotNull().cast(self._native_dtypes.IntegerType()) for col in cols),\n )\n return true_divide(F, numerator, denominator)\n\n return self._expr._from_elementwise_horizontal_op(func, *exprs)\n\n def concat(\n self, items: Iterable[SparkLikeLazyFrame], *, how: ConcatMethod\n ) -> SparkLikeLazyFrame:\n dfs = [item._native_frame for item in items]\n if how == "vertical":\n cols_0 = dfs[0].columns\n for i, df in enumerate(dfs[1:], start=1):\n cols_current = df.columns\n if not ((len(cols_current) == len(cols_0)) and (cols_current == cols_0)):\n msg = (\n "unable to vstack, column names don't match:\n"\n f" - dataframe 0: {cols_0}\n"\n f" - dataframe {i}: {cols_current}\n"\n )\n raise TypeError(msg)\n\n return SparkLikeLazyFrame(\n native_dataframe=reduce(lambda x, y: x.union(y), dfs),\n backend_version=self._backend_version,\n version=self._version,\n implementation=self._implementation,\n )\n\n if how == "diagonal":\n return SparkLikeLazyFrame(\n native_dataframe=reduce(\n lambda x, y: x.unionByName(y, allowMissingColumns=True), dfs\n ),\n backend_version=self._backend_version,\n version=self._version,\n implementation=self._implementation,\n )\n raise NotImplementedError\n\n def concat_str(\n self, *exprs: SparkLikeExpr, separator: str, ignore_nulls: bool\n ) -> SparkLikeExpr:\n def func(df: SparkLikeLazyFrame) -> list[Column]:\n cols = [s for _expr in exprs for s in _expr(df)]\n cols_casted = [s.cast(df._native_dtypes.StringType()) for s in cols]\n null_mask = [df._F.isnull(s) for s in cols]\n\n if not ignore_nulls:\n null_mask_result = reduce(operator.or_, null_mask)\n result = df._F.when(\n ~null_mask_result,\n reduce(\n lambda x, y: df._F.format_string(f"%s{separator}%s", x, y),\n cols_casted,\n ),\n ).otherwise(df._F.lit(None))\n else:\n init_value, *values = [\n df._F.when(~nm, col).otherwise(df._F.lit(""))\n for col, nm in zip(cols_casted, null_mask)\n ]\n\n separators = (\n df._F.when(nm, df._F.lit("")).otherwise(df._F.lit(separator))\n for nm in null_mask[:-1]\n )\n result = reduce(\n lambda x, y: df._F.format_string("%s%s", x, y),\n (\n df._F.format_string("%s%s", s, v)\n for s, v in zip(separators, values)\n ),\n init_value,\n )\n\n return [result]\n\n return self._expr(\n call=func,\n evaluate_output_names=combine_evaluate_output_names(*exprs),\n alias_output_names=combine_alias_output_names(*exprs),\n backend_version=self._backend_version,\n version=self._version,\n implementation=self._implementation,\n )\n\n def when(self, predicate: SparkLikeExpr) -> SparkLikeWhen:\n return SparkLikeWhen.from_expr(predicate, context=self)\n\n\nclass SparkLikeWhen(LazyWhen[SparkLikeLazyFrame, "Column", SparkLikeExpr]):\n @property\n def _then(self) -> type[SparkLikeThen]:\n return SparkLikeThen\n\n def __call__(self, df: SparkLikeLazyFrame) -> Sequence[Column]:\n self.when = df._F.when\n self.lit = df._F.lit\n return super().__call__(df)\n\n def _window_function(\n self, df: SparkLikeLazyFrame, window_inputs: SparkWindowInputs\n ) -> Sequence[Column]:\n self.when = df._F.when\n self.lit = df._F.lit\n return super()._window_function(df, window_inputs)\n\n\nclass SparkLikeThen(\n LazyThen[SparkLikeLazyFrame, "Column", SparkLikeExpr], SparkLikeExpr\n): ...\n | .venv\Lib\site-packages\narwhals\_spark_like\namespace.py | namespace.py | Python | 9,724 | 0.95 | 0.213235 | 0.004425 | awesome-app | 733 | 2023-10-17T10:27:52.020218 | MIT | false | f57109063c1ce26bf59f8298219b2b3a |
from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom narwhals._compliant import CompliantSelector, LazySelectorNamespace\nfrom narwhals._spark_like.expr import SparkLikeExpr\n\nif TYPE_CHECKING:\n from sqlframe.base.column import Column # noqa: F401\n\n from narwhals._spark_like.dataframe import SparkLikeLazyFrame # noqa: F401\n\n\nclass SparkLikeSelectorNamespace(LazySelectorNamespace["SparkLikeLazyFrame", "Column"]):\n @property\n def _selector(self) -> type[SparkLikeSelector]:\n return SparkLikeSelector\n\n\nclass SparkLikeSelector(CompliantSelector["SparkLikeLazyFrame", "Column"], SparkLikeExpr): # type: ignore[misc]\n def _to_expr(self) -> SparkLikeExpr:\n return SparkLikeExpr(\n self._call,\n evaluate_output_names=self._evaluate_output_names,\n alias_output_names=self._alias_output_names,\n backend_version=self._backend_version,\n version=self._version,\n implementation=self._implementation,\n )\n | .venv\Lib\site-packages\narwhals\_spark_like\selectors.py | selectors.py | Python | 1,018 | 0.95 | 0.172414 | 0 | vue-tools | 649 | 2024-08-15T15:30:12.831154 | GPL-3.0 | false | 4cb2a58d0c281cd9b3d189703f903705 |
from __future__ import annotations\n\nimport operator\nfrom functools import lru_cache\nfrom importlib import import_module\nfrom typing import TYPE_CHECKING, Any, overload\n\nfrom narwhals._utils import Implementation, isinstance_or_issubclass\nfrom narwhals.exceptions import UnsupportedDTypeError\n\nif TYPE_CHECKING:\n from types import ModuleType\n\n import sqlframe.base.types as sqlframe_types\n from sqlframe.base.column import Column\n from sqlframe.base.session import _BaseSession as Session\n from typing_extensions import TypeAlias\n\n from narwhals._spark_like.dataframe import SparkLikeLazyFrame\n from narwhals._spark_like.expr import SparkLikeExpr\n from narwhals._utils import Version\n from narwhals.dtypes import DType\n from narwhals.typing import IntoDType\n\n _NativeDType: TypeAlias = sqlframe_types.DataType\n SparkSession = Session[Any, Any, Any, Any, Any, Any, Any]\n\nUNITS_DICT = {\n "y": "year",\n "q": "quarter",\n "mo": "month",\n "d": "day",\n "h": "hour",\n "m": "minute",\n "s": "second",\n "ms": "millisecond",\n "us": "microsecond",\n "ns": "nanosecond",\n}\n\n# see https://spark.apache.org/docs/latest/sql-ref-datetime-pattern.html\n# and https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior\nDATETIME_PATTERNS_MAPPING = {\n "%Y": "yyyy", # Year with century (4 digits)\n "%y": "yy", # Year without century (2 digits)\n "%m": "MM", # Month (01-12)\n "%d": "dd", # Day of the month (01-31)\n "%H": "HH", # Hour (24-hour clock) (00-23)\n "%I": "hh", # Hour (12-hour clock) (01-12)\n "%M": "mm", # Minute (00-59)\n "%S": "ss", # Second (00-59)\n "%f": "S", # Microseconds -> Milliseconds\n "%p": "a", # AM/PM\n "%a": "E", # Abbreviated weekday name\n "%A": "E", # Full weekday name\n "%j": "D", # Day of the year\n "%z": "Z", # Timezone offset\n "%s": "X", # Unix timestamp\n}\n\n\n# NOTE: don't lru_cache this as `ModuleType` isn't hashable\ndef native_to_narwhals_dtype( # noqa: C901, PLR0912\n dtype: _NativeDType, version: Version, spark_types: ModuleType, session: SparkSession\n) -> DType:\n dtypes = version.dtypes\n if TYPE_CHECKING:\n native = sqlframe_types\n else:\n native = spark_types\n\n if isinstance(dtype, native.DoubleType):\n return dtypes.Float64()\n if isinstance(dtype, native.FloatType):\n return dtypes.Float32()\n if isinstance(dtype, native.LongType):\n return dtypes.Int64()\n if isinstance(dtype, native.IntegerType):\n return dtypes.Int32()\n if isinstance(dtype, native.ShortType):\n return dtypes.Int16()\n if isinstance(dtype, native.ByteType):\n return dtypes.Int8()\n if isinstance(dtype, (native.StringType, native.VarcharType, native.CharType)):\n return dtypes.String()\n if isinstance(dtype, native.BooleanType):\n return dtypes.Boolean()\n if isinstance(dtype, native.DateType):\n return dtypes.Date()\n if isinstance(dtype, native.TimestampNTZType):\n # TODO(marco): cover this\n return dtypes.Datetime() # pragma: no cover\n if isinstance(dtype, native.TimestampType):\n return dtypes.Datetime(time_zone=fetch_session_time_zone(session))\n if isinstance(dtype, native.DecimalType):\n # TODO(marco): cover this\n return dtypes.Decimal() # pragma: no cover\n if isinstance(dtype, native.ArrayType):\n return dtypes.List(\n inner=native_to_narwhals_dtype(\n dtype.elementType, version, spark_types, session\n )\n )\n if isinstance(dtype, native.StructType):\n return dtypes.Struct(\n fields=[\n dtypes.Field(\n name=field.name,\n dtype=native_to_narwhals_dtype(\n field.dataType, version, spark_types, session\n ),\n )\n for field in dtype\n ]\n )\n if isinstance(dtype, native.BinaryType):\n return dtypes.Binary()\n return dtypes.Unknown() # pragma: no cover\n\n\n@lru_cache(maxsize=4)\ndef fetch_session_time_zone(session: SparkSession) -> str:\n # Timezone can't be changed in PySpark session, so this can be cached.\n try:\n return session.conf.get("spark.sql.session.timeZone") # type: ignore[attr-defined]\n except Exception: # noqa: BLE001\n # https://github.com/eakmanrq/sqlframe/issues/406\n return "<unknown>"\n\n\ndef narwhals_to_native_dtype( # noqa: C901, PLR0912\n dtype: IntoDType, version: Version, spark_types: ModuleType\n) -> _NativeDType:\n dtypes = version.dtypes\n if TYPE_CHECKING:\n native = sqlframe_types\n else:\n native = spark_types\n\n if isinstance_or_issubclass(dtype, dtypes.Float64):\n return native.DoubleType()\n if isinstance_or_issubclass(dtype, dtypes.Float32):\n return native.FloatType()\n if isinstance_or_issubclass(dtype, dtypes.Int64):\n return native.LongType()\n if isinstance_or_issubclass(dtype, dtypes.Int32):\n return native.IntegerType()\n if isinstance_or_issubclass(dtype, dtypes.Int16):\n return native.ShortType()\n if isinstance_or_issubclass(dtype, dtypes.Int8):\n return native.ByteType()\n if isinstance_or_issubclass(dtype, dtypes.String):\n return native.StringType()\n if isinstance_or_issubclass(dtype, dtypes.Boolean):\n return native.BooleanType()\n if isinstance_or_issubclass(dtype, dtypes.Date):\n return native.DateType()\n if isinstance_or_issubclass(dtype, dtypes.Datetime):\n dt_time_zone = dtype.time_zone\n if dt_time_zone is None:\n return native.TimestampNTZType()\n if dt_time_zone != "UTC": # pragma: no cover\n msg = f"Only UTC time zone is supported for PySpark, got: {dt_time_zone}"\n raise ValueError(msg)\n return native.TimestampType()\n if isinstance_or_issubclass(dtype, (dtypes.List, dtypes.Array)):\n return native.ArrayType(\n elementType=narwhals_to_native_dtype(\n dtype.inner, version=version, spark_types=native\n )\n )\n if isinstance_or_issubclass(dtype, dtypes.Struct): # pragma: no cover\n return native.StructType(\n fields=[\n native.StructField(\n name=field.name,\n dataType=narwhals_to_native_dtype(\n field.dtype, version=version, spark_types=native\n ),\n )\n for field in dtype.fields\n ]\n )\n if isinstance_or_issubclass(dtype, dtypes.Binary):\n return native.BinaryType()\n\n if isinstance_or_issubclass(\n dtype,\n (\n dtypes.UInt64,\n dtypes.UInt32,\n dtypes.UInt16,\n dtypes.UInt8,\n dtypes.Enum,\n dtypes.Categorical,\n dtypes.Time,\n ),\n ): # pragma: no cover\n msg = "Unsigned integer, Enum, Categorical and Time types are not supported by spark-like backend"\n raise UnsupportedDTypeError(msg)\n\n msg = f"Unknown dtype: {dtype}" # pragma: no cover\n raise AssertionError(msg)\n\n\ndef evaluate_exprs(\n df: SparkLikeLazyFrame, /, *exprs: SparkLikeExpr\n) -> list[tuple[str, Column]]:\n native_results: list[tuple[str, Column]] = []\n\n for expr in exprs:\n native_series_list = expr._call(df)\n output_names = expr._evaluate_output_names(df)\n if expr._alias_output_names is not None:\n output_names = expr._alias_output_names(output_names)\n if len(output_names) != len(native_series_list): # pragma: no cover\n msg = f"Internal error: got output names {output_names}, but only got {len(native_series_list)} results"\n raise AssertionError(msg)\n native_results.extend(zip(output_names, native_series_list))\n\n return native_results\n\n\ndef import_functions(implementation: Implementation, /) -> ModuleType:\n if implementation is Implementation.PYSPARK:\n from pyspark.sql import functions\n\n return functions\n if implementation is Implementation.PYSPARK_CONNECT:\n from pyspark.sql.connect import functions\n\n return functions\n from sqlframe.base.session import _BaseSession\n\n return import_module(f"sqlframe.{_BaseSession().execution_dialect_name}.functions")\n\n\ndef import_native_dtypes(implementation: Implementation, /) -> ModuleType:\n if implementation is Implementation.PYSPARK:\n from pyspark.sql import types\n\n return types\n if implementation is Implementation.PYSPARK_CONNECT:\n from pyspark.sql.connect import types\n\n return types\n from sqlframe.base.session import _BaseSession\n\n return import_module(f"sqlframe.{_BaseSession().execution_dialect_name}.types")\n\n\ndef import_window(implementation: Implementation, /) -> type[Any]:\n if implementation is Implementation.PYSPARK:\n from pyspark.sql import Window\n\n return Window\n\n if implementation is Implementation.PYSPARK_CONNECT:\n from pyspark.sql.connect.window import Window\n\n return Window\n from sqlframe.base.session import _BaseSession\n\n return import_module(\n f"sqlframe.{_BaseSession().execution_dialect_name}.window"\n ).Window\n\n\n@overload\ndef strptime_to_pyspark_format(format: None) -> None: ...\n\n\n@overload\ndef strptime_to_pyspark_format(format: str) -> str: ...\n\n\ndef strptime_to_pyspark_format(format: str | None) -> str | None:\n """Converts a Python strptime datetime format string to a PySpark datetime format string."""\n if format is None: # pragma: no cover\n return None\n\n # Replace Python format specifiers with PySpark specifiers\n pyspark_format = format\n for py_format, spark_format in DATETIME_PATTERNS_MAPPING.items():\n pyspark_format = pyspark_format.replace(py_format, spark_format)\n return pyspark_format.replace("T", " ")\n\n\ndef true_divide(F: Any, left: Column, right: Column) -> Column: # noqa: N803\n # PySpark before 3.5 doesn't have `try_divide`, SQLFrame doesn't have it.\n divide = getattr(F, "try_divide", operator.truediv)\n return divide(left, right)\n | .venv\Lib\site-packages\narwhals\_spark_like\utils.py | utils.py | Python | 10,175 | 0.95 | 0.205479 | 0.036735 | awesome-app | 652 | 2024-11-12T06:13:06.564526 | BSD-3-Clause | false | feef225579b775e6ad613c218b820c5c |
\n\n | .venv\Lib\site-packages\narwhals\_spark_like\__pycache__\dataframe.cpython-313.pyc | dataframe.cpython-313.pyc | Other | 27,356 | 0.95 | 0.013274 | 0.009434 | awesome-app | 243 | 2024-07-08T15:13:20.479728 | MIT | false | 663fc518d2c186267ec3bd9a57dd00d4 |
\n\n | .venv\Lib\site-packages\narwhals\_spark_like\__pycache__\expr.cpython-313.pyc | expr.cpython-313.pyc | Other | 51,122 | 0.95 | 0.002985 | 0 | awesome-app | 150 | 2024-01-26T10:52:59.859877 | Apache-2.0 | false | 2d8da6f697259eb674f2e8055a8000a5 |
\n\n | .venv\Lib\site-packages\narwhals\_spark_like\__pycache__\expr_dt.cpython-313.pyc | expr_dt.cpython-313.pyc | Other | 13,405 | 0.8 | 0.068966 | 0 | awesome-app | 579 | 2024-03-22T18:36:20.797015 | MIT | false | e5f27667ffdd89230c19de3da24d365c |
\n\n | .venv\Lib\site-packages\narwhals\_spark_like\__pycache__\expr_list.cpython-313.pyc | expr_list.cpython-313.pyc | Other | 1,129 | 0.7 | 0 | 0 | awesome-app | 529 | 2025-03-05T11:13:19.251931 | BSD-3-Clause | false | 84aa81a242ea7f247e3433459add3424 |
\n\n | .venv\Lib\site-packages\narwhals\_spark_like\__pycache__\expr_str.cpython-313.pyc | expr_str.cpython-313.pyc | Other | 10,526 | 0.95 | 0 | 0 | react-lib | 478 | 2024-08-31T17:36:41.668808 | Apache-2.0 | false | 0c73bb0fb5830a89bf76bf4198a32b2f |
\n\n | .venv\Lib\site-packages\narwhals\_spark_like\__pycache__\expr_struct.cpython-313.pyc | expr_struct.cpython-313.pyc | Other | 1,409 | 0.7 | 0 | 0 | vue-tools | 299 | 2024-04-02T06:01:48.966077 | BSD-3-Clause | false | 8685275463cbd7ae788c7260e0bd7593 |
\n\n | .venv\Lib\site-packages\narwhals\_spark_like\__pycache__\group_by.cpython-313.pyc | group_by.cpython-313.pyc | Other | 2,415 | 0.7 | 0 | 0 | awesome-app | 287 | 2025-01-07T03:29:37.377944 | MIT | false | 9126e2d12aff551860f87331f46b8d14 |
\n\n | .venv\Lib\site-packages\narwhals\_spark_like\__pycache__\namespace.cpython-313.pyc | namespace.cpython-313.pyc | Other | 16,900 | 0.95 | 0 | 0.021978 | node-utils | 332 | 2024-08-08T22:48:33.175431 | Apache-2.0 | false | 8f8711e68a796836ece692f2cc8d9064 |
\n\n | .venv\Lib\site-packages\narwhals\_spark_like\__pycache__\selectors.cpython-313.pyc | selectors.cpython-313.pyc | Other | 1,836 | 0.8 | 0 | 0 | node-utils | 389 | 2023-09-10T20:22:19.065636 | GPL-3.0 | false | 2d4cae31c2d2e0fb676f5e593adac72f |
\n\n | .venv\Lib\site-packages\narwhals\_spark_like\__pycache__\utils.cpython-313.pyc | utils.cpython-313.pyc | Other | 11,868 | 0.95 | 0.010101 | 0.022989 | awesome-app | 647 | 2023-09-19T17:39:48.868281 | GPL-3.0 | false | f50309e41fc5ef599e7e8bd65dd4a63c |
\n\n | .venv\Lib\site-packages\narwhals\_spark_like\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 195 | 0.7 | 0 | 0 | vue-tools | 941 | 2025-06-13T11:29:10.658208 | GPL-3.0 | false | 64a0a37bf92de9b3d8791edcf49ca7c6 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\dependencies.cpython-313.pyc | dependencies.cpython-313.pyc | Other | 25,360 | 0.95 | 0.100418 | 0.005 | awesome-app | 839 | 2023-08-22T04:17:18.796712 | Apache-2.0 | false | 4cad4badd6c88c1f454a23fabd4fd48c |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\dtypes.cpython-313.pyc | dtypes.cpython-313.pyc | Other | 32,018 | 0.95 | 0.047722 | 0 | awesome-app | 624 | 2023-11-11T23:28:38.753142 | MIT | false | f3e5bdf4cde5cfa1db97cfa6f517cac8 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\exceptions.cpython-313.pyc | exceptions.cpython-313.pyc | Other | 7,675 | 0.95 | 0.130435 | 0 | awesome-app | 98 | 2024-11-12T12:57:11.546359 | MIT | false | fdc023b2de4798b3194c6960b6003cae |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\expr_cat.cpython-313.pyc | expr_cat.cpython-313.pyc | Other | 2,048 | 0.95 | 0 | 0 | node-utils | 797 | 2024-11-20T20:10:30.907608 | BSD-3-Clause | false | 1d9177432a729d0b7467a9b8f9271c35 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\expr_dt.cpython-313.pyc | expr_dt.cpython-313.pyc | Other | 34,417 | 0.95 | 0.018767 | 0 | node-utils | 252 | 2025-01-01T01:06:08.914704 | MIT | false | 1ecc9db3ae45fba8357a155bedf380ea |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\expr_list.cpython-313.pyc | expr_list.cpython-313.pyc | Other | 2,520 | 0.95 | 0 | 0 | react-lib | 563 | 2024-02-27T01:55:39.112664 | Apache-2.0 | false | aa5323205627b44823589d2bd74ad626 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\expr_name.cpython-313.pyc | expr_name.cpython-313.pyc | Other | 7,785 | 0.95 | 0.013514 | 0 | react-lib | 278 | 2024-09-19T16:38:03.270531 | MIT | false | 0ab2607c0e261e9af7aa383864ee346f |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\expr_str.cpython-313.pyc | expr_str.cpython-313.pyc | Other | 23,694 | 0.95 | 0.016032 | 0.00232 | react-lib | 566 | 2023-08-09T07:05:30.902766 | BSD-3-Clause | false | a4b8629f85374f82ce56ecbd40586393 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\expr_struct.cpython-313.pyc | expr_struct.cpython-313.pyc | Other | 2,558 | 0.85 | 0 | 0 | node-utils | 197 | 2023-12-19T09:35:21.897890 | Apache-2.0 | false | c77f32d659de0991b9f85134236734c9 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\functions.cpython-313.pyc | functions.cpython-313.pyc | Other | 71,124 | 0.75 | 0.050512 | 0.015088 | vue-tools | 655 | 2024-04-26T14:13:52.076499 | MIT | false | 91bee92a255b7d9eb6400bcedb2b99fa |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\group_by.cpython-313.pyc | group_by.cpython-313.pyc | Other | 8,499 | 0.95 | 0.02381 | 0 | vue-tools | 432 | 2024-08-08T00:48:10.238224 | MIT | false | fea3e08cdcd17476009d3b6e17b5c284 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\schema.cpython-313.pyc | schema.cpython-313.pyc | Other | 7,786 | 0.95 | 0.006452 | 0.014815 | python-kit | 578 | 2025-03-04T06:13:04.002170 | BSD-3-Clause | false | 0285619cc2e375c36d84cafe65515621 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\selectors.cpython-313.pyc | selectors.cpython-313.pyc | Other | 12,896 | 0.95 | 0.00823 | 0.014563 | node-utils | 899 | 2023-09-06T15:01:17.086972 | GPL-3.0 | false | 9fc78f13c084e5f8c2e656a564197d6e |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\series.cpython-313.pyc | series.cpython-313.pyc | Other | 91,673 | 0.75 | 0.028381 | 0.001551 | awesome-app | 360 | 2023-07-19T02:06:54.437841 | GPL-3.0 | false | 95e0696fa734565b6909fda8d2530f3c |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\series_cat.cpython-313.pyc | series_cat.cpython-313.pyc | Other | 1,565 | 0.95 | 0 | 0 | python-kit | 540 | 2023-08-21T13:52:22.296166 | BSD-3-Clause | false | caae58ad977226efce8508c24486f090 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\series_dt.cpython-313.pyc | series_dt.cpython-313.pyc | Other | 24,637 | 0.95 | 0.03481 | 0 | vue-tools | 989 | 2023-12-11T17:56:58.451105 | MIT | false | e3bfdb43e89dcb7b98bb1c8edc010147 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\series_list.cpython-313.pyc | series_list.cpython-313.pyc | Other | 1,642 | 0.95 | 0 | 0 | python-kit | 430 | 2023-10-19T09:01:42.995378 | MIT | false | ea788aeb3235cea9329824a1ef661d89 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\series_str.cpython-313.pyc | series_str.cpython-313.pyc | Other | 17,652 | 0.95 | 0.030303 | 0.002653 | vue-tools | 321 | 2025-01-06T19:07:28.734887 | BSD-3-Clause | false | be122f13eea05bef5b34774e7b6ad8a9 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\series_struct.cpython-313.pyc | series_struct.cpython-313.pyc | Other | 1,626 | 0.95 | 0 | 0 | react-lib | 575 | 2023-10-25T09:37:46.493354 | Apache-2.0 | false | 72c1354586a38ec0f7d55e27e63b6f2c |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\this.cpython-313.pyc | this.cpython-313.pyc | Other | 1,774 | 0.7 | 0.0625 | 0 | node-utils | 285 | 2024-07-02T14:35:42.864154 | BSD-3-Clause | false | 89c0e7a4672f437d083b1491643350e9 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\translate.cpython-313.pyc | translate.cpython-313.pyc | Other | 28,695 | 0.95 | 0.067308 | 0.010929 | react-lib | 660 | 2025-06-07T02:37:42.065831 | BSD-3-Clause | false | 2a09dade2c697159ea54ac38b51ace13 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\typing.cpython-313.pyc | typing.cpython-313.pyc | Other | 12,021 | 0.8 | 0 | 0 | vue-tools | 722 | 2023-10-28T17:35:33.805293 | GPL-3.0 | false | 135edc1f2f6335e321902ddbc93de934 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\utils.cpython-313.pyc | utils.cpython-313.pyc | Other | 351 | 0.7 | 0 | 0 | node-utils | 290 | 2025-01-22T19:30:10.348819 | Apache-2.0 | false | 55897aedb70c91bfa73b633f261ec07f |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\_constants.cpython-313.pyc | _constants.cpython-313.pyc | Other | 774 | 0.7 | 0 | 0 | react-lib | 982 | 2024-07-23T09:17:24.585648 | BSD-3-Clause | false | 88648ac0066acd41906ef1a7284faa77 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\_duration.cpython-313.pyc | _duration.cpython-313.pyc | Other | 2,356 | 0.8 | 0.153846 | 0 | node-utils | 884 | 2024-07-24T11:06:23.207901 | Apache-2.0 | false | 8bed2dcd9979dc3d7dea87739cabd958 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\_enum.cpython-313.pyc | _enum.cpython-313.pyc | Other | 1,754 | 0.95 | 0.16129 | 0 | react-lib | 793 | 2025-04-01T11:39:21.722275 | BSD-3-Clause | false | 625c855903ae97c697c2525df7ef0fb3 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\_expression_parsing.cpython-313.pyc | _expression_parsing.cpython-313.pyc | Other | 24,264 | 0.95 | 0 | 0.005348 | vue-tools | 181 | 2023-12-02T20:27:08.304861 | GPL-3.0 | false | 800d9dc7c1a7b29217eb0e3988194568 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\_namespace.cpython-313.pyc | _namespace.cpython-313.pyc | Other | 23,048 | 0.95 | 0 | 0.05036 | vue-tools | 177 | 2025-06-24T11:40:26.598898 | MIT | false | aa05cafb4cf1cc36c66ce4aec613b822 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\_translate.cpython-313.pyc | _translate.cpython-313.pyc | Other | 9,125 | 0.95 | 0.09901 | 0.047619 | react-lib | 659 | 2024-08-30T20:46:47.848881 | BSD-3-Clause | false | c5e1766c1b2d60b36fa2ad3c55a798b3 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\_typing_compat.cpython-313.pyc | _typing_compat.cpython-313.pyc | Other | 3,083 | 0.8 | 0.016949 | 0.036364 | node-utils | 479 | 2025-04-09T20:54:12.145116 | GPL-3.0 | false | 6f60c24ce093759a707b17fea8c5d873 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\_utils.cpython-313.pyc | _utils.cpython-313.pyc | Other | 83,155 | 0.75 | 0.053321 | 0.007511 | react-lib | 717 | 2024-04-25T19:10:05.971808 | BSD-3-Clause | false | b2fde1bb77cc4fa5cf606f12311b1bf9 |
\n\n | .venv\Lib\site-packages\narwhals\__pycache__\__init__.cpython-313.pyc | __init__.cpython-313.pyc | Other | 3,165 | 0.95 | 0 | 0 | react-lib | 601 | 2023-12-31T11:27:09.101835 | MIT | false | 663a7dea3b71b6178ea99691b80a447f |
pip\n | .venv\Lib\site-packages\narwhals-1.45.0.dist-info\INSTALLER | INSTALLER | Other | 4 | 0.5 | 0 | 0 | python-kit | 38 | 2025-02-23T02:45:53.912680 | Apache-2.0 | false | 365c9bfeb7d89244f2ce01c1de44cb85 |
Metadata-Version: 2.4\nName: narwhals\nVersion: 1.45.0\nSummary: Extremely lightweight compatibility layer between dataframe libraries\nProject-URL: Homepage, https://github.com/narwhals-dev/narwhals\nProject-URL: Documentation, https://narwhals-dev.github.io/narwhals/\nProject-URL: Repository, https://github.com/narwhals-dev/narwhals\nProject-URL: Bug Tracker, https://github.com/narwhals-dev/narwhals/issues\nAuthor-email: Marco Gorelli <hello_narwhals@proton.me>\nLicense-File: LICENSE.md\nKeywords: cudf,dask,dataframes,interoperability,modin,pandas,polars,pyarrow\nClassifier: License :: OSI Approved :: MIT License\nClassifier: Operating System :: OS Independent\nClassifier: Programming Language :: Python\nClassifier: Typing :: Typed\nRequires-Python: >=3.9\nProvides-Extra: cudf\nRequires-Dist: cudf>=24.10.0; extra == 'cudf'\nProvides-Extra: dask\nRequires-Dist: dask[dataframe]>=2024.8; extra == 'dask'\nProvides-Extra: duckdb\nRequires-Dist: duckdb>=1.0; extra == 'duckdb'\nProvides-Extra: ibis\nRequires-Dist: ibis-framework>=6.0.0; extra == 'ibis'\nRequires-Dist: packaging; extra == 'ibis'\nRequires-Dist: pyarrow-hotfix; extra == 'ibis'\nRequires-Dist: rich; extra == 'ibis'\nProvides-Extra: modin\nRequires-Dist: modin; extra == 'modin'\nProvides-Extra: pandas\nRequires-Dist: pandas>=1.1.3; extra == 'pandas'\nProvides-Extra: polars\nRequires-Dist: polars>=0.20.4; extra == 'polars'\nProvides-Extra: pyarrow\nRequires-Dist: pyarrow>=11.0.0; extra == 'pyarrow'\nProvides-Extra: pyspark\nRequires-Dist: pyspark>=3.5.0; extra == 'pyspark'\nProvides-Extra: pyspark-connect\nRequires-Dist: pyspark[connect]>=3.5.0; extra == 'pyspark-connect'\nProvides-Extra: sqlframe\nRequires-Dist: sqlframe>=3.22.0; extra == 'sqlframe'\nDescription-Content-Type: text/markdown\n\n# Narwhals\n\n<h1 align="center">\n <img\n width="400"\n alt="narwhals_small"\n src="https://github.com/narwhals-dev/narwhals/assets/33491632/26be901e-5383-49f2-9fbd-5c97b7696f27">\n</h1>\n\n[](https://badge.fury.io/py/narwhals)\n[](https://pepy.tech/project/narwhals)\n[](https://peps.python.org/pep-0740/)\n[](https://pypi.org/project/narwhals)\n\nExtremely lightweight and extensible compatibility layer between dataframe libraries!\n\n- **Full API support**: cuDF, Modin, pandas, Polars, PyArrow.\n- **Lazy-only support**: Dask, DuckDB, Ibis, PySpark, SQLFrame. Work in progress: Daft.\n\nSeamlessly support all, without depending on any!\n\n- ✅ **Just use** [a subset of **the Polars API**](https://narwhals-dev.github.io/narwhals/api-reference/), no need to learn anything new\n- ✅ **Zero dependencies**, Narwhals only uses what\n the user passes in so your library can stay lightweight\n- ✅ Separate **lazy** and eager APIs, use **expressions**\n- ✅ Support pandas' complicated type system and index, without\n either getting in the way\n- ✅ **100% branch coverage**, tested against pandas and Polars nightly builds\n- ✅ **Negligible overhead**, see [overhead](https://narwhals-dev.github.io/narwhals/overhead/)\n- ✅ Let your IDE help you thanks to **full static typing**, see [typing](https://narwhals-dev.github.io/narwhals/api-reference/typing/)\n- ✅ **Perfect backwards compatibility policy**,\n see [stable api](https://narwhals-dev.github.io/narwhals/backcompat/) for how to opt-in\n\nGet started!\n\n- [Read the documentation](https://narwhals-dev.github.io/narwhals/)\n- [Chat with us on Discord!](https://discord.gg/V3PqtB4VA4)\n- [Join our community call](https://calendar.google.com/calendar/embed?src=27ff6dc5f598c1d94c1f6e627a1aaae680e2fac88f848bda1f2c7946ae74d5ab%40group.calendar.google.com)\n- [Read the contributing guide](https://github.com/narwhals-dev/narwhals/blob/main/CONTRIBUTING.md)\n\n<details>\n<summary>Table of contents</summary>\n\n- [Narwhals](#narwhals)\n - [Installation](#installation)\n - [Usage](#usage)\n - [Example](#example)\n - [Scope](#scope)\n - [Roadmap](#roadmap)\n - [Used by](#used-by)\n - [Sponsors and institutional partners](#sponsors-and-institutional-partners)\n - [Appears on](#appears-on)\n - [Why "Narwhals"?](#why-narwhals)\n\n</details>\n\n## Installation\n\n- pip (recommended, as it's the most up-to-date)\n ```\n pip install narwhals\n ```\n- conda-forge (also fine, but the latest version may take longer to appear)\n ```\n conda install -c conda-forge narwhals\n ```\n\n## Usage\n\nThere are three steps to writing dataframe-agnostic code using Narwhals:\n\n1. use `narwhals.from_native` to wrap a pandas/Polars/Modin/cuDF/PyArrow\n DataFrame/LazyFrame in a Narwhals class\n2. use the [subset of the Polars API supported by Narwhals](https://narwhals-dev.github.io/narwhals/api-reference/)\n3. use `narwhals.to_native` to return an object to the user in its original\n dataframe flavour. For example:\n\n - if you started with pandas, you'll get pandas back\n - if you started with Polars, you'll get Polars back\n - if you started with Modin, you'll get Modin back (and compute will be distributed)\n - if you started with cuDF, you'll get cuDF back (and compute will happen on GPU)\n - if you started with PyArrow, you'll get PyArrow back\n\n<h1 align="left">\n <img\n width="600"\n alt="narwhals_gif"\n src="https://github.com/user-attachments/assets/88292d3c-6359-4155-973d-d0f8e3fbf5ac">\n\n</h1>\n\n## Example\n\nNarwhals allows you to define dataframe-agnostic functions. For example:\n\n```python\nimport narwhals as nw\nfrom narwhals.typing import IntoFrameT\n\n\ndef agnostic_function(\n df_native: IntoFrameT,\n date_column: str,\n price_column: str,\n) -> IntoFrameT:\n return (\n nw.from_native(df_native)\n .group_by(nw.col(date_column).dt.truncate("1mo"))\n .agg(nw.col(price_column).mean())\n .sort(date_column)\n .to_native()\n )\n```\n\nYou can then pass `pandas.DataFrame`, `polars.DataFrame`, `polars.LazyFrame`, `duckdb.DuckDBPyRelation`,\n`pyspark.sql.DataFrame`, `pyarrow.Table`, and more, to `agnostic_function`. In each case, no additional\ndependencies will be required, and computation will stay native to the input library:\n\n```python\nimport pandas as pd\nimport polars as pl\nfrom datetime import datetime\n\ndata = {\n "date": [datetime(2020, 1, 1), datetime(2020, 1, 8), datetime(2020, 2, 3)],\n "price": [1, 4, 3],\n}\nprint("pandas result:")\nprint(agnostic_function(pd.DataFrame(data), "date", "price"))\nprint()\nprint("Polars result:")\nprint(agnostic_function(pl.DataFrame(data), "date", "price"))\n```\n\n```terminal\npandas result:\n date price\n0 2020-01-01 2.5\n1 2020-02-01 3.0\n\nPolars result:\nshape: (2, 2)\n┌─────────────────────┬───────┐\n│ date ┆ price │\n│ --- ┆ --- │\n│ datetime[μs] ┆ f64 │\n╞═════════════════════╪═══════╡\n│ 2020-01-01 00:00:00 ┆ 2.5 │\n│ 2020-02-01 00:00:00 ┆ 3.0 │\n└─────────────────────┴───────┘\n```\n\nSee the [tutorial](https://narwhals-dev.github.io/narwhals/basics/dataframe/) for several examples!\n\n## Scope\n\n- Do you maintain a dataframe-consuming library?\n- Do you have a specific Polars function in mind that you would like Narwhals to have in order to make your work easier?\n\nIf you said yes to both, we'd love to hear from you!\n\n## Roadmap\n\nSee [roadmap discussion on GitHub](https://github.com/narwhals-dev/narwhals/discussions/1370)\nfor an up-to-date plan of future work.\n\n## Used by\n\nJoin the party!\n\n- [altair](https://github.com/vega/altair/)\n- [bokeh](https://github.com/bokeh/bokeh)\n- [darts](https://github.com/unit8co/darts)\n- [hierarchicalforecast](https://github.com/Nixtla/hierarchicalforecast)\n- [marimo](https://github.com/marimo-team/marimo)\n- [metalearners](https://github.com/Quantco/metalearners)\n- [panel-graphic-walker](https://github.com/panel-extensions/panel-graphic-walker)\n- [plotly](https://plotly.com)\n- [pointblank](https://github.com/posit-dev/pointblank)\n- [pymarginaleffects](https://github.com/vincentarelbundock/pymarginaleffects)\n- [py-shiny](https://github.com/posit-dev/py-shiny)\n- [rio](https://github.com/rio-labs/rio)\n- [scikit-lego](https://github.com/koaning/scikit-lego)\n- [scikit-playtime](https://github.com/koaning/scikit-playtime)\n- [tabmat](https://github.com/Quantco/tabmat)\n- [tea-tasting](https://github.com/e10v/tea-tasting)\n- [timebasedcv](https://github.com/FBruzzesi/timebasedcv)\n- [tubular](https://github.com/lvgig/tubular)\n- [Validoopsie](https://github.com/akmalsoliev/Validoopsie)\n- [vegafusion](https://github.com/vega/vegafusion)\n- [wimsey](https://github.com/benrutter/wimsey)\n\nFeel free to add your project to the list if it's missing, and/or\n[chat with us on Discord](https://discord.gg/V3PqtB4VA4) if you'd like any support.\n\n## Sponsors and institutional partners\n\nNarwhals is 100% independent, community-driven, and community-owned.\nWe are extremely grateful to the following organisations for having\nprovided some funding / development time:\n\n- [Quansight Labs](https://labs.quansight.org)\n- [Quansight Futures](https://www.qi.ventures)\n- [OpenTeams](https://www.openteams.com)\n- [POSSEE initiative](https://possee.org)\n- [BYU-Idaho](https://www.byui.edu)\n\nIf you contribute to Narwhals on your organization's time, please let us know. We'd be happy to add your employer\nto this list!\n\n## Appears on\n\nNarwhals has been featured in several talks, podcasts, and blog posts:\n\n- [Talk Python to me Podcast](https://youtu.be/FSH7BZ0tuE0)\n Ahoy, Narwhals are bridging the data science APIs\n\n- [Python Bytes Podcast](https://www.youtube.com/live/N7w_ESVW40I?si=y-wN1uCsAuJOKlOT&t=382)\n Episode 402, topic #2\n\n- [Super Data Science: ML & AI Podcast](https://www.youtube.com/watch?v=TeG4U8R0U8U) \n Narwhals: For Pandas-to-Polars DataFrame Compatibility\n\n- [Sample Space Podcast | probabl](https://youtu.be/8hYdq4sWbbQ?si=WG0QP1CZ6gkFf18b) \n How Narwhals has many end users ... that never use it directly. - Marco Gorelli\n\n- [The Real Python Podcast](https://www.youtube.com/watch?v=w5DFZbFYzCM)\n Narwhals: Expanding DataFrame Compatibility Between Libraries\n\n- [Pycon Lithuania](https://www.youtube.com/watch?v=-mdx7Cn6_6E) \n Marco Gorelli - DataFrame interoperatiblity - what's been achieved, and what comes next?\n\n- [Pycon Italy](https://www.youtube.com/watch?v=3IqUli9XsmQ) \n How you can write a dataframe-agnostic library - Marco Gorelli\n\n- [Polars Blog Post](https://pola.rs/posts/lightweight_plotting/) \n Polars has a new lightweight plotting backend\n\n- [Quansight Labs blog post (w/ Scikit-Lego)](https://labs.quansight.org/blog/scikit-lego-narwhals) \n How Narwhals and scikit-lego came together to achieve dataframe-agnosticism\n\n## Why "Narwhals"?\n\n[Coz they are so awesome](https://youtu.be/ykwqXuMPsoc?si=A-i8LdR38teYsos4).\n\nThanks to [Olha Urdeichuk](https://www.fiverr.com/olhaurdeichuk) for the illustration!\n | .venv\Lib\site-packages\narwhals-1.45.0.dist-info\METADATA | METADATA | Other | 11,103 | 0.95 | 0.051903 | 0.04329 | vue-tools | 542 | 2023-08-15T23:58:52.440619 | Apache-2.0 | false | 1f250a69e852cbde00d680c583b32bdd |
narwhals-1.45.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4\nnarwhals-1.45.0.dist-info/METADATA,sha256=ABWRwvyVLVo8dTaLyiHKerK_uaqF19R1hr4K2n_rBDE,11103\nnarwhals-1.45.0.dist-info/RECORD,,\nnarwhals-1.45.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87\nnarwhals-1.45.0.dist-info/licenses/LICENSE.md,sha256=heMD6hta6RzeBucppx59AUCgr_ukRY0ABj0bcrN3mKs,1071\nnarwhals/__init__.py,sha256=lmD4l3YwOdbC7IHfiIK0BKigKAQO9tyBqIXjHIji-zY,3226\nnarwhals/__pycache__/__init__.cpython-313.pyc,,\nnarwhals/__pycache__/_constants.cpython-313.pyc,,\nnarwhals/__pycache__/_duration.cpython-313.pyc,,\nnarwhals/__pycache__/_enum.cpython-313.pyc,,\nnarwhals/__pycache__/_expression_parsing.cpython-313.pyc,,\nnarwhals/__pycache__/_namespace.cpython-313.pyc,,\nnarwhals/__pycache__/_translate.cpython-313.pyc,,\nnarwhals/__pycache__/_typing_compat.cpython-313.pyc,,\nnarwhals/__pycache__/_utils.cpython-313.pyc,,\nnarwhals/__pycache__/dataframe.cpython-313.pyc,,\nnarwhals/__pycache__/dependencies.cpython-313.pyc,,\nnarwhals/__pycache__/dtypes.cpython-313.pyc,,\nnarwhals/__pycache__/exceptions.cpython-313.pyc,,\nnarwhals/__pycache__/expr.cpython-313.pyc,,\nnarwhals/__pycache__/expr_cat.cpython-313.pyc,,\nnarwhals/__pycache__/expr_dt.cpython-313.pyc,,\nnarwhals/__pycache__/expr_list.cpython-313.pyc,,\nnarwhals/__pycache__/expr_name.cpython-313.pyc,,\nnarwhals/__pycache__/expr_str.cpython-313.pyc,,\nnarwhals/__pycache__/expr_struct.cpython-313.pyc,,\nnarwhals/__pycache__/functions.cpython-313.pyc,,\nnarwhals/__pycache__/group_by.cpython-313.pyc,,\nnarwhals/__pycache__/schema.cpython-313.pyc,,\nnarwhals/__pycache__/selectors.cpython-313.pyc,,\nnarwhals/__pycache__/series.cpython-313.pyc,,\nnarwhals/__pycache__/series_cat.cpython-313.pyc,,\nnarwhals/__pycache__/series_dt.cpython-313.pyc,,\nnarwhals/__pycache__/series_list.cpython-313.pyc,,\nnarwhals/__pycache__/series_str.cpython-313.pyc,,\nnarwhals/__pycache__/series_struct.cpython-313.pyc,,\nnarwhals/__pycache__/this.cpython-313.pyc,,\nnarwhals/__pycache__/translate.cpython-313.pyc,,\nnarwhals/__pycache__/typing.cpython-313.pyc,,\nnarwhals/__pycache__/utils.cpython-313.pyc,,\nnarwhals/_arrow/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\nnarwhals/_arrow/__pycache__/__init__.cpython-313.pyc,,\nnarwhals/_arrow/__pycache__/dataframe.cpython-313.pyc,,\nnarwhals/_arrow/__pycache__/expr.cpython-313.pyc,,\nnarwhals/_arrow/__pycache__/group_by.cpython-313.pyc,,\nnarwhals/_arrow/__pycache__/namespace.cpython-313.pyc,,\nnarwhals/_arrow/__pycache__/selectors.cpython-313.pyc,,\nnarwhals/_arrow/__pycache__/series.cpython-313.pyc,,\nnarwhals/_arrow/__pycache__/series_cat.cpython-313.pyc,,\nnarwhals/_arrow/__pycache__/series_dt.cpython-313.pyc,,\nnarwhals/_arrow/__pycache__/series_list.cpython-313.pyc,,\nnarwhals/_arrow/__pycache__/series_str.cpython-313.pyc,,\nnarwhals/_arrow/__pycache__/series_struct.cpython-313.pyc,,\nnarwhals/_arrow/__pycache__/typing.cpython-313.pyc,,\nnarwhals/_arrow/__pycache__/utils.cpython-313.pyc,,\nnarwhals/_arrow/dataframe.py,sha256=4ZcAD446X1-wVQz1RPLkmfscLuXJVHnvcwmCm7G1bjE,28247\nnarwhals/_arrow/expr.py,sha256=djbbrYnXYdfWwIU8ApcciwHdwp3xG7560Q1EaB_UWrY,7925\nnarwhals/_arrow/group_by.py,sha256=2rVZ2HjBpyTIA1rZu53mXhNVn6eb-irPUppwJ013-JI,6555\nnarwhals/_arrow/namespace.py,sha256=DQg519CcbvFLQBAjdKZNhdCqU_NixBpfk5XrfKWBn3A,11581\nnarwhals/_arrow/selectors.py,sha256=adTwvKdjojRAaBPTywKdICQEdqv4hRUW2qvUjP7FOqA,1011\nnarwhals/_arrow/series.py,sha256=bL7scaNmNGJqEoQCTYh3CcGZKWatpH1HeTVuaP8POX4,44983\nnarwhals/_arrow/series_cat.py,sha256=vvNlPaHHcA-ORzh_79-oY03wt6aIg1rLI0At8FXr2Ok,598\nnarwhals/_arrow/series_dt.py,sha256=pzDV4FlIcCpzLJMwg2x0Ohvdd1Vrzrik8EESfeGegUo,7956\nnarwhals/_arrow/series_list.py,sha256=EpSul8DmTjQW00NQ5nLn9ZBSSUR0uuZ0IK6TLX1utwI,421\nnarwhals/_arrow/series_str.py,sha256=eputVlf0eq9f9mu1YmJK9vG_rm4JZXSLW_sLfYsg6HA,4178\nnarwhals/_arrow/series_struct.py,sha256=85pQSUqOdeMyjsnjaSr_4YBC2HRGD-dsnNy2tPveJRM,410\nnarwhals/_arrow/typing.py,sha256=TmgG8eqF4uCRW5NFzWTiBvlUGvD46govtIC8gRyrkmA,2286\nnarwhals/_arrow/utils.py,sha256=Ta6rfNT8DXMVagmBs8BGBfKG9hmzf1PMAFX3eyOioUM,16640\nnarwhals/_compliant/__init__.py,sha256=aVjWIMakgpdSJd08jlYDm79HZDckFpTybP7bopLnEuk,1901\nnarwhals/_compliant/__pycache__/__init__.cpython-313.pyc,,\nnarwhals/_compliant/__pycache__/any_namespace.cpython-313.pyc,,\nnarwhals/_compliant/__pycache__/dataframe.cpython-313.pyc,,\nnarwhals/_compliant/__pycache__/expr.cpython-313.pyc,,\nnarwhals/_compliant/__pycache__/group_by.cpython-313.pyc,,\nnarwhals/_compliant/__pycache__/namespace.cpython-313.pyc,,\nnarwhals/_compliant/__pycache__/selectors.cpython-313.pyc,,\nnarwhals/_compliant/__pycache__/series.cpython-313.pyc,,\nnarwhals/_compliant/__pycache__/typing.cpython-313.pyc,,\nnarwhals/_compliant/__pycache__/when_then.cpython-313.pyc,,\nnarwhals/_compliant/__pycache__/window.cpython-313.pyc,,\nnarwhals/_compliant/any_namespace.py,sha256=UVN-25ZCV6Z7b8oEW0DqeiSxPXy--hF0ZP0xd2XPef0,3459\nnarwhals/_compliant/dataframe.py,sha256=wOfNIEtv2UulY3lun9033uvjzGZ9kSVKMbV9170lKPg,17529\nnarwhals/_compliant/expr.py,sha256=C0g_zwyw2HGCNBUz8kIfXRNJ8wycjp2jOq9yEEs77HE,42464\nnarwhals/_compliant/group_by.py,sha256=wyPs_oZh_YfZpEVb82Zv-7QehZKUFhoQF6dtA5XZ4iE,8303\nnarwhals/_compliant/namespace.py,sha256=lyv7m12OpjuBDu2Bu9GUNEpW9fopfCBXdUMFhnMac7w,6986\nnarwhals/_compliant/selectors.py,sha256=4jYyUKrJHXldcmXpK3cjhoEjcGHMQSC6oI16AV0quD4,12018\nnarwhals/_compliant/series.py,sha256=IZrv0UGiSHlv4kDncglmvoO8tArBlXHtDk3Keas-aZs,14017\nnarwhals/_compliant/typing.py,sha256=S66PZCMV9J-jGAgZ-njFCe2nMy4_W4lHiHGHXXbkGGM,6131\nnarwhals/_compliant/when_then.py,sha256=NzXNJaXhow5s9gyIgLRytNqrqLND2HqID0KALYHxuAE,8172\nnarwhals/_compliant/window.py,sha256=PUQ22r050YATk2ZjQFW8n1PlFZ9K-cFW26O7kOGuWtg,477\nnarwhals/_constants.py,sha256=kE1KWsIky4ryabH-Z117ZtGW24ccTcreWOZJjpacO6I,1094\nnarwhals/_dask/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\nnarwhals/_dask/__pycache__/__init__.cpython-313.pyc,,\nnarwhals/_dask/__pycache__/dataframe.cpython-313.pyc,,\nnarwhals/_dask/__pycache__/expr.cpython-313.pyc,,\nnarwhals/_dask/__pycache__/expr_dt.cpython-313.pyc,,\nnarwhals/_dask/__pycache__/expr_str.cpython-313.pyc,,\nnarwhals/_dask/__pycache__/group_by.cpython-313.pyc,,\nnarwhals/_dask/__pycache__/namespace.cpython-313.pyc,,\nnarwhals/_dask/__pycache__/selectors.cpython-313.pyc,,\nnarwhals/_dask/__pycache__/utils.cpython-313.pyc,,\nnarwhals/_dask/dataframe.py,sha256=JhxqPqsSZUcSE_8F6yFeStkwcMa88me_4_sXGEmsEFo,17761\nnarwhals/_dask/expr.py,sha256=1sFqPPV8pOLIpmvpkpGxVW0MYGEIO9guoa7eOts0p90,25598\nnarwhals/_dask/expr_dt.py,sha256=K1dIKBYZDLMesHI5M1V1W3x59hZVCs4FkHAElEZDEL0,6277\nnarwhals/_dask/expr_str.py,sha256=4qtqegf33ATmplOsiQRMVkalTJupUBukAa9GeVbPTJE,3563\nnarwhals/_dask/group_by.py,sha256=wu72jvAY-9dxPtV-ywXsynAnjBsQu94S9lGNdMEYopA,4297\nnarwhals/_dask/namespace.py,sha256=u-L4za3etVkmAqrhDAUmyn7BBDya_4g-AcuvET0yv7M,13387\nnarwhals/_dask/selectors.py,sha256=p-1eITSnrq-OQrJ9rAiUSfSeyy55yPiMTlDmXCYZA0M,984\nnarwhals/_dask/utils.py,sha256=V5k1DnF_ey0vK9FK_oRSpmtlwmquirxQgDuK0ep91ig,6716\nnarwhals/_duckdb/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\nnarwhals/_duckdb/__pycache__/__init__.cpython-313.pyc,,\nnarwhals/_duckdb/__pycache__/dataframe.cpython-313.pyc,,\nnarwhals/_duckdb/__pycache__/expr.cpython-313.pyc,,\nnarwhals/_duckdb/__pycache__/expr_dt.cpython-313.pyc,,\nnarwhals/_duckdb/__pycache__/expr_list.cpython-313.pyc,,\nnarwhals/_duckdb/__pycache__/expr_str.cpython-313.pyc,,\nnarwhals/_duckdb/__pycache__/expr_struct.cpython-313.pyc,,\nnarwhals/_duckdb/__pycache__/group_by.cpython-313.pyc,,\nnarwhals/_duckdb/__pycache__/namespace.cpython-313.pyc,,\nnarwhals/_duckdb/__pycache__/selectors.cpython-313.pyc,,\nnarwhals/_duckdb/__pycache__/series.cpython-313.pyc,,\nnarwhals/_duckdb/__pycache__/typing.cpython-313.pyc,,\nnarwhals/_duckdb/__pycache__/utils.cpython-313.pyc,,\nnarwhals/_duckdb/dataframe.py,sha256=s3lHrhkQ3kgI4p0M0W9JuJBnLi2yB7oB9HXWmTxIa1M,19153\nnarwhals/_duckdb/expr.py,sha256=r4UOFivuVVIUro3jwiXJOFA4W5p27ZRZX_-qKrcPVEk,30085\nnarwhals/_duckdb/expr_dt.py,sha256=Zmngw2y60ZDXG2U30YupLpmpu0X6c8jERzDQnCOCthQ,5546\nnarwhals/_duckdb/expr_list.py,sha256=nc29I5a_k9GtizpksBMHOOnnkA3TLb0RP5KJ9fI2j4k,498\nnarwhals/_duckdb/expr_str.py,sha256=d3VAmH4ClWtY4A_5BFg2706y1Jkog3PBiQ0VFK45tvQ,4559\nnarwhals/_duckdb/expr_struct.py,sha256=NTTpqrn4r5rSzcGuypOw2kDfq1cdqlZtdkihgDfjU3U,578\nnarwhals/_duckdb/group_by.py,sha256=s4zQulWKM2veH_ynUsqOJz5vuMdS_HSwYnpLpsB8-D8,1122\nnarwhals/_duckdb/namespace.py,sha256=TiwJKwoLP6u7GwfAMRickfJbVWpFfr0-7jGGf55U2us,7126\nnarwhals/_duckdb/selectors.py,sha256=iwNJ0vb5AKGdbzJHrMG4da-bI2VWHxBjhjgV8ppExUM,967\nnarwhals/_duckdb/series.py,sha256=xBpuPUnSSIQ1vYEKjHQFZN7ix1ZyMwSchliDPpkf3Wk,1397\nnarwhals/_duckdb/typing.py,sha256=JC4Zfke7WRUgVF4CC25MnBRUFwKdV8WD4IxSNU8YQgo,420\nnarwhals/_duckdb/utils.py,sha256=NzBMKH5ehQlfgFbW4roW-nXXluwDJ-JTQuIe3JVvqt4,12006\nnarwhals/_duration.py,sha256=9xqXxT2i6Imfry8eIh_xTMlZSiXHxGjlFWQB2uOIqDY,2008\nnarwhals/_enum.py,sha256=sUR-04yIwjAMsX5eelKnc1UKXc5dBoj1do0krubAE04,1192\nnarwhals/_expression_parsing.py,sha256=X-5VV_3knecN0XfYUdXACqGlEFX_Xw4HPP2gV41FW5s,21828\nnarwhals/_ibis/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\nnarwhals/_ibis/__pycache__/__init__.cpython-313.pyc,,\nnarwhals/_ibis/__pycache__/dataframe.cpython-313.pyc,,\nnarwhals/_ibis/__pycache__/expr.cpython-313.pyc,,\nnarwhals/_ibis/__pycache__/expr_dt.cpython-313.pyc,,\nnarwhals/_ibis/__pycache__/expr_list.cpython-313.pyc,,\nnarwhals/_ibis/__pycache__/expr_str.cpython-313.pyc,,\nnarwhals/_ibis/__pycache__/expr_struct.cpython-313.pyc,,\nnarwhals/_ibis/__pycache__/group_by.cpython-313.pyc,,\nnarwhals/_ibis/__pycache__/namespace.cpython-313.pyc,,\nnarwhals/_ibis/__pycache__/selectors.cpython-313.pyc,,\nnarwhals/_ibis/__pycache__/series.cpython-313.pyc,,\nnarwhals/_ibis/__pycache__/utils.cpython-313.pyc,,\nnarwhals/_ibis/dataframe.py,sha256=wFs9-4Ka1fOqXXfUt9etMpJ5qB-BieH9eZvY2SUzyd8,16359\nnarwhals/_ibis/expr.py,sha256=XOxHmOnEnO1gfgDFxHh4FfGrhKaKOOaRTg1-WqXDNnw,24351\nnarwhals/_ibis/expr_dt.py,sha256=If06DxHTWAhXAewNF_iXDpXkeCPTAfVIlJAVszFUQOY,3761\nnarwhals/_ibis/expr_list.py,sha256=8OY2idSAWaa3-nlAItCAWwldPL1dV4iEf2Cc42nNScE,442\nnarwhals/_ibis/expr_str.py,sha256=Ir5RiyEzMFqDGGg5sCovupr18BEuMPP5HMV-U0SKgJU,5034\nnarwhals/_ibis/expr_struct.py,sha256=2EsMh-V42kYoBLYb_Zt8PB8qCbgmZuoIZ93F7J5WQrw,570\nnarwhals/_ibis/group_by.py,sha256=1vSgGA9awkbQV2gesr_G_CxUsV2ulLqTQJ8yj5GFnOE,1030\nnarwhals/_ibis/namespace.py,sha256=9CZsng10mkbwBvN6b2VB8gZTpxBTsf7kjqHIEOeyVTU,6766\nnarwhals/_ibis/selectors.py,sha256=W9bKXeYuA3vGmraDP9WLloZ4WtdsC8GcO0v822fQW_I,901\nnarwhals/_ibis/series.py,sha256=CZDwDPsdELKtdr7OWmcFyGqexr33Ucfnv_RU95VJxIQ,1218\nnarwhals/_ibis/utils.py,sha256=0GBrwbwoaAx-EErzoTIAq73e-zW4TS3YhD4ub66Bwxs,8277\nnarwhals/_interchange/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\nnarwhals/_interchange/__pycache__/__init__.cpython-313.pyc,,\nnarwhals/_interchange/__pycache__/dataframe.cpython-313.pyc,,\nnarwhals/_interchange/__pycache__/series.cpython-313.pyc,,\nnarwhals/_interchange/dataframe.py,sha256=GWlbo9OqzQh-Y-uevJ1Kr762oaFHqFJSc3ql00LDH9w,5921\nnarwhals/_interchange/series.py,sha256=nSxdlOZrw3wtavS42TMR_b_EGgPBv224ioZBMo5eoC8,1651\nnarwhals/_namespace.py,sha256=BjX_8vtWYsG4JT_LA8TkaCyEeIwFMeBwS-B_ENFRNvI,15711\nnarwhals/_pandas_like/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\nnarwhals/_pandas_like/__pycache__/__init__.cpython-313.pyc,,\nnarwhals/_pandas_like/__pycache__/dataframe.cpython-313.pyc,,\nnarwhals/_pandas_like/__pycache__/expr.cpython-313.pyc,,\nnarwhals/_pandas_like/__pycache__/group_by.cpython-313.pyc,,\nnarwhals/_pandas_like/__pycache__/namespace.cpython-313.pyc,,\nnarwhals/_pandas_like/__pycache__/selectors.cpython-313.pyc,,\nnarwhals/_pandas_like/__pycache__/series.cpython-313.pyc,,\nnarwhals/_pandas_like/__pycache__/series_cat.cpython-313.pyc,,\nnarwhals/_pandas_like/__pycache__/series_dt.cpython-313.pyc,,\nnarwhals/_pandas_like/__pycache__/series_list.cpython-313.pyc,,\nnarwhals/_pandas_like/__pycache__/series_str.cpython-313.pyc,,\nnarwhals/_pandas_like/__pycache__/series_struct.cpython-313.pyc,,\nnarwhals/_pandas_like/__pycache__/typing.cpython-313.pyc,,\nnarwhals/_pandas_like/__pycache__/utils.cpython-313.pyc,,\nnarwhals/_pandas_like/dataframe.py,sha256=OqkWloDKax5mFPy8WaQzeuugKHZgXtWRVhXZMAdsmnc,41915\nnarwhals/_pandas_like/expr.py,sha256=jNEMvF5OyRlP_yj72kBkrka2s7TIB58hFgThGjyfRI8,16230\nnarwhals/_pandas_like/group_by.py,sha256=_BaVTlUOc_d40w0dvLrFDLb5LUZj6tXpr2GEkGMZlBc,12747\nnarwhals/_pandas_like/namespace.py,sha256=AdjWJbnUyfapVD-lgsYFezjGr4WS5QjNOna42DIadJs,16149\nnarwhals/_pandas_like/selectors.py,sha256=5tKYNWYPrZ3dgarWbE3U8MGbxdxrgijvcUQu4wFPeGc,1144\nnarwhals/_pandas_like/series.py,sha256=nu9hi-tMUoFsr_xtFf1EXUA6nNI2hzSqgJoHhU_FG78,42479\nnarwhals/_pandas_like/series_cat.py,sha256=MJwCnJ49hfnODh6JgMHOCQ2KBlTbmySU6_X4XWaqiz4,527\nnarwhals/_pandas_like/series_dt.py,sha256=jMgZbpuuLcEpCVHYtrA3WgURCO4wJS8yVyfg-dFisNI,9769\nnarwhals/_pandas_like/series_list.py,sha256=iriDqAN3SEq8UOiYyC8kl2q1-OZn2LBY2SlWDoFnp20,1138\nnarwhals/_pandas_like/series_str.py,sha256=r_iqLsVZt29ZqGKKcdHupqlror_C8VDU04twU48L3dc,3680\nnarwhals/_pandas_like/series_struct.py,sha256=vX9HoO42vHackvVozUfp8odM9uJ4owct49ydKDnohdk,518\nnarwhals/_pandas_like/typing.py,sha256=Awm2YnewvdA3l_4SEwb_5AithhwBYNx1t1ajaHnvUsM,1064\nnarwhals/_pandas_like/utils.py,sha256=TggCZly0iM3yC-2ZoZm9f4RjFiRswyx2Vw-xFIJTj54,25428\nnarwhals/_polars/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\nnarwhals/_polars/__pycache__/__init__.cpython-313.pyc,,\nnarwhals/_polars/__pycache__/dataframe.cpython-313.pyc,,\nnarwhals/_polars/__pycache__/expr.cpython-313.pyc,,\nnarwhals/_polars/__pycache__/group_by.cpython-313.pyc,,\nnarwhals/_polars/__pycache__/namespace.cpython-313.pyc,,\nnarwhals/_polars/__pycache__/series.cpython-313.pyc,,\nnarwhals/_polars/__pycache__/typing.cpython-313.pyc,,\nnarwhals/_polars/__pycache__/utils.cpython-313.pyc,,\nnarwhals/_polars/dataframe.py,sha256=fG1gg6tF6af4KaegE5Muk3ZeZcX22zdMfA20dQYy2As,22293\nnarwhals/_polars/expr.py,sha256=sLujMbQiyjXZqOmEwkrlOjgI9c9bxgMh_5y4qsMsKWM,16673\nnarwhals/_polars/group_by.py,sha256=v88hD-rOCNtCeT_YqMVII2V1c1B5TEwd0s6qOa1yXb4,2491\nnarwhals/_polars/namespace.py,sha256=i-oncEd6ch5UsxbYb2CzbKAGH2ch___xwCZxCip3Tu4,11606\nnarwhals/_polars/series.py,sha256=Qj5Z5diA5z7PkMBqCKOemiwaOBZ1H4ZWUBe7duHh9jU,25564\nnarwhals/_polars/typing.py,sha256=iBAA0Z0FT6vG4Zxn-Z9pCLcHnrkKtyIUAeM-mOxlBJU,655\nnarwhals/_polars/utils.py,sha256=elocLSqc1uPRZk6pYT8FpCBYufPxy4yUkqA3RwYiCsQ,8836\nnarwhals/_spark_like/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\nnarwhals/_spark_like/__pycache__/__init__.cpython-313.pyc,,\nnarwhals/_spark_like/__pycache__/dataframe.cpython-313.pyc,,\nnarwhals/_spark_like/__pycache__/expr.cpython-313.pyc,,\nnarwhals/_spark_like/__pycache__/expr_dt.cpython-313.pyc,,\nnarwhals/_spark_like/__pycache__/expr_list.cpython-313.pyc,,\nnarwhals/_spark_like/__pycache__/expr_str.cpython-313.pyc,,\nnarwhals/_spark_like/__pycache__/expr_struct.cpython-313.pyc,,\nnarwhals/_spark_like/__pycache__/group_by.cpython-313.pyc,,\nnarwhals/_spark_like/__pycache__/namespace.cpython-313.pyc,,\nnarwhals/_spark_like/__pycache__/selectors.cpython-313.pyc,,\nnarwhals/_spark_like/__pycache__/utils.cpython-313.pyc,,\nnarwhals/_spark_like/dataframe.py,sha256=iT4UQ7inqonuRrXTJDYERwKhwwQfIISWenSd3VD3raw,20325\nnarwhals/_spark_like/expr.py,sha256=W9ZvXqaEUgMKFX_gmbcZRCcz7Q6x6fmTOKCotpoKbL0,33165\nnarwhals/_spark_like/expr_dt.py,sha256=X0jlPzip-lhrfYYrQZfT8dP5YcdIdU-_qu9sydKX8TE,8002\nnarwhals/_spark_like/expr_list.py,sha256=nq3uORNG6M_p-fUfqOVMWJblBmbULMyZSOjN3dvhfAs,481\nnarwhals/_spark_like/expr_str.py,sha256=WWApNS8hMKJLRCrjA4s-9hSCNXRyow64tGRLIIv9GdE,5578\nnarwhals/_spark_like/expr_struct.py,sha256=GZ8y1BSeaiFCBp0PGj2MbTvo4tguaRfP10h6jQi02xQ,615\nnarwhals/_spark_like/group_by.py,sha256=DJsR4558F8jsiaEQHpox09heEvWKuG39aAPQq-Tqel4,1245\nnarwhals/_spark_like/namespace.py,sha256=JVFxztsr69JkUSGSrdeQ_195MfnIpOZMKozSwls6f6I,9724\nnarwhals/_spark_like/selectors.py,sha256=odBRkCQR3gXtSLg59uDZxybI5skZi7I2QObQC4nwP78,1018\nnarwhals/_spark_like/utils.py,sha256=xRmW3PfPh7UpOLj8lAAozpcifv5at5zDLeEerH5pHVI,10175\nnarwhals/_translate.py,sha256=e8RjNCNX4QGJWKjM6VANDTG_bVT2VusjNfjsnkCBO3g,6112\nnarwhals/_typing_compat.py,sha256=ZZgMwNcF7RCjBnsVoMl1rAH7ZB2DYFM3jkLC5g0Cmfc,2916\nnarwhals/_utils.py,sha256=j-UEiSpuyhlHXZZlDYOUOVmvQz17NUDmKAt-dAG4XI8,66589\nnarwhals/dataframe.py,sha256=DldEqpn-V3s_D5_eAMfC5KTYfQZ_yDv1wLgrBOOtgMs,127443\nnarwhals/dependencies.py,sha256=ZG1p0GI8ko2zLWodzOjLZTHFRFWlCKwmL_XxVdAhQA0,18697\nnarwhals/dtypes.py,sha256=q76kn1IaU-hROpPP7xhWTPncdKF9FG5OXxZ1aXSzEBk,23320\nnarwhals/exceptions.py,sha256=XoiIk4kxpV_OlkOitBR3Vgr3UjjgnrGL7r9OH6RgUK4,4455\nnarwhals/expr.py,sha256=y1NbFYeliXbDsF6kSJX32pTdOjbVE-UiIYhcbsH7Kqs,107051\nnarwhals/expr_cat.py,sha256=E0FooLjYVXQ69U0Cb38_6Kiu0F-9-VwXGkjJXXV9klE,1261\nnarwhals/expr_dt.py,sha256=PRcNelO21RAD3vTa57egHDXEChi8uksWhaXWphk8WO4,31229\nnarwhals/expr_list.py,sha256=E0_B0tXtL4KtfKIUk7u1llC-qHENoHTjlpX3zs0laoA,1772\nnarwhals/expr_name.py,sha256=nB09yF61KMWV0pcM8u3ex3maCtnFuryTyDKr0GwToSo,6012\nnarwhals/expr_str.py,sha256=d5zDutOC4UNjQmd8bG3uVtqmFeYIcVSZQgjI1mZKpVs,20335\nnarwhals/expr_struct.py,sha256=O5GbmFra17OCJEcG9wo3rVKS2vIRqI7z0SM17aSUmrM,1793\nnarwhals/functions.py,sha256=Z_kxAoIzEJQzN2bE1vDaRFIQT5cZ-4VhhYyi1WyX_sY,68710\nnarwhals/group_by.py,sha256=4Hmiap6ri94owOWkps4ODQTbxMKKJUW56Hb_DEAgYJo,7258\nnarwhals/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\nnarwhals/schema.py,sha256=_KvNPN6ndaW859JQRBfMOa-lgnXJxdJWJlkYd3B3DFk,6488\nnarwhals/selectors.py,sha256=ybbFG7Sjebr8qoMgD43O6QuHBGl52yUpGRe08L1LKyo,10759\nnarwhals/series.py,sha256=wCtA3PQSBtEGVAuh6oQzdc4-Ps5pVaZkbtSZ92hlgl0,90312\nnarwhals/series_cat.py,sha256=I5osb8Fj04iWqfEWjiyhVPiFYe3Kk_mTZXZjwn3jnRc,911\nnarwhals/series_dt.py,sha256=9EAEP2dP9yxMQu3snmufwS0Y9inqMQ8B9EayEdvBMtw,24109\nnarwhals/series_list.py,sha256=NznN1Z50RSGX4uQBO4OBMtu7YBHRM58tgPKoJjmOrDg,1041\nnarwhals/series_str.py,sha256=rl8KlB5z_iGFGWNtsy3OxdkXZWfxOpVhhRkHIbqfmDw,16565\nnarwhals/series_struct.py,sha256=pmKigkmKe8m-40X9UWW5_8PLqNzHIKubElv2V2Ohu4I,974\nnarwhals/stable/__init__.py,sha256=b9soCkGkQzgF5jO5EdQ6IOQpnc6G6eqWmY6WwpoSjhk,85\nnarwhals/stable/__pycache__/__init__.cpython-313.pyc,,\nnarwhals/stable/v1/__init__.py,sha256=ur9eUu8DdSUquNNDkW8X_ccHjtRE9HWZIHL5gVPzuBk,60635\nnarwhals/stable/v1/__pycache__/__init__.cpython-313.pyc,,\nnarwhals/stable/v1/__pycache__/_dtypes.cpython-313.pyc,,\nnarwhals/stable/v1/__pycache__/_namespace.cpython-313.pyc,,\nnarwhals/stable/v1/__pycache__/dependencies.cpython-313.pyc,,\nnarwhals/stable/v1/__pycache__/dtypes.cpython-313.pyc,,\nnarwhals/stable/v1/__pycache__/selectors.cpython-313.pyc,,\nnarwhals/stable/v1/__pycache__/typing.cpython-313.pyc,,\nnarwhals/stable/v1/_dtypes.py,sha256=7zGmarnurUTgY6DI4KQ1MSAC7B9ZZiI5Em7plb-HAEs,2700\nnarwhals/stable/v1/_namespace.py,sha256=gfsbT4R4aLmmdArY35LRpEHPiUeZKEEnXGiY9ypFtwE,296\nnarwhals/stable/v1/dependencies.py,sha256=aM0IShF4hbaaMEDRJQXvsu4RABZOdBG4QhrpJPxb7fg,5001\nnarwhals/stable/v1/dtypes.py,sha256=u2NFDJyCkjsK6p3K9ULJS7CoG16z0Z1MQiACTVkhkH4,1082\nnarwhals/stable/v1/selectors.py,sha256=xEA9bBzkpTwUanGGoFwBCcHIAXb8alwrPX1mjzE9mDM,312\nnarwhals/stable/v1/typing.py,sha256=HFIIvrvir15JN6jVDMgEPV7Fry3TQSPz7l47yzP-7Ms,6896\nnarwhals/this.py,sha256=BbKcj0ReWqE01lznzKjuqq7otXONvjBevWWC5aJhQxs,1584\nnarwhals/translate.py,sha256=TKdYRfN1MDsXKvI82hQZSL7DM3D500nSri-5disiJME,27442\nnarwhals/typing.py,sha256=YYajUDHIrMaa1pFbshvWjPThanZDNN71mUenCg_kaXI,15334\nnarwhals/utils.py,sha256=2GT3XxucWI6l9r9jTwMw7Aha2G73FsSXgXNFZ3O_ZyA,223\n | .venv\Lib\site-packages\narwhals-1.45.0.dist-info\RECORD | RECORD | Other | 19,794 | 0.85 | 0 | 0 | node-utils | 12 | 2025-04-04T09:17:24.504666 | BSD-3-Clause | false | cd914513318c90c6634acf0e0d04400d |
Wheel-Version: 1.0\nGenerator: hatchling 1.27.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n | .venv\Lib\site-packages\narwhals-1.45.0.dist-info\WHEEL | WHEEL | Other | 87 | 0.5 | 0 | 0 | python-kit | 375 | 2024-08-25T09:53:24.863231 | BSD-3-Clause | false | e2fcb0ad9ea59332c808928b4b439e7a |
MIT License\n\nCopyright (c) 2024, Marco Gorelli\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n | .venv\Lib\site-packages\narwhals-1.45.0.dist-info\licenses\LICENSE.md | LICENSE.md | Markdown | 1,071 | 0.7 | 0 | 0 | react-lib | 926 | 2024-10-20T19:26:56.772829 | MIT | false | 70f2b43719c3b55b87337bfe5d3744bd |
"""nbclient cli."""\nfrom __future__ import annotations\n\nimport logging\nimport sys\nimport typing\nfrom pathlib import Path\nfrom textwrap import dedent\n\nimport nbformat\nfrom jupyter_core.application import JupyterApp\nfrom traitlets import Bool, Integer, List, Unicode, default\nfrom traitlets.config import catch_config_error\n\nfrom nbclient import __version__\n\nfrom .client import NotebookClient\n\n# mypy: disable-error-code="no-untyped-call"\n\nnbclient_aliases: dict[str, str] = {\n "timeout": "NbClientApp.timeout",\n "startup_timeout": "NbClientApp.startup_timeout",\n "kernel_name": "NbClientApp.kernel_name",\n "output": "NbClientApp.output_base",\n}\n\nnbclient_flags: dict[str, typing.Any] = {\n "allow-errors": (\n {\n "NbClientApp": {\n "allow_errors": True,\n },\n },\n "Errors are ignored and execution is continued until the end of the notebook.",\n ),\n "inplace": (\n {\n "NbClientApp": {\n "inplace": True,\n },\n },\n "Overwrite input notebook with executed results.",\n ),\n}\n\n\nclass NbClientApp(JupyterApp):\n """\n An application used to execute notebook files (``*.ipynb``)\n """\n\n version = Unicode(__version__)\n name = "jupyter-execute"\n aliases = nbclient_aliases\n flags = nbclient_flags\n\n description = "An application used to execute notebook files (*.ipynb)"\n notebooks = List(Unicode(), help="Path of notebooks to convert").tag(config=True)\n timeout = Integer(\n None,\n allow_none=True,\n help=dedent(\n """\n The time to wait (in seconds) for output from executions.\n If a cell execution takes longer, a TimeoutError is raised.\n ``-1`` will disable the timeout.\n """\n ),\n ).tag(config=True)\n startup_timeout = Integer(\n 60,\n help=dedent(\n """\n The time to wait (in seconds) for the kernel to start.\n If kernel startup takes longer, a RuntimeError is\n raised.\n """\n ),\n ).tag(config=True)\n allow_errors = Bool(\n False,\n help=dedent(\n """\n When a cell raises an error the default behavior is that\n execution is stopped and a :py:class:`nbclient.exceptions.CellExecutionError`\n is raised.\n If this flag is provided, errors are ignored and execution\n is continued until the end of the notebook.\n """\n ),\n ).tag(config=True)\n skip_cells_with_tag = Unicode(\n "skip-execution",\n help=dedent(\n """\n Name of the cell tag to use to denote a cell that should be skipped.\n """\n ),\n ).tag(config=True)\n kernel_name = Unicode(\n "",\n help=dedent(\n """\n Name of kernel to use to execute the cells.\n If not set, use the kernel_spec embedded in the notebook.\n """\n ),\n ).tag(config=True)\n inplace = Bool(\n False,\n help=dedent(\n """\n Default is execute notebook without writing the newly executed notebook.\n If this flag is provided, the newly generated notebook will\n overwrite the input notebook.\n """\n ),\n ).tag(config=True)\n output_base = Unicode(\n None,\n allow_none=True,\n help=dedent(\n """\n Write executed notebook to this file base name.\n Supports pattern replacements ``'{notebook_name}'``,\n the name of the input notebook file without extension.\n Note that output is always relative to the parent directory of the\n input notebook.\n """\n ),\n ).tag(config=True)\n\n @default("log_level")\n def _log_level_default(self) -> int:\n return logging.INFO\n\n @catch_config_error\n def initialize(self, argv: list[str] | None = None) -> None:\n """Initialize the app."""\n super().initialize(argv)\n\n # Get notebooks to run\n self.notebooks = self.get_notebooks()\n\n # If there are none, throw an error\n if not self.notebooks:\n sys.exit(-1)\n\n # If output, must have single notebook\n if len(self.notebooks) > 1 and self.output_base is not None:\n if "{notebook_name}" not in self.output_base:\n msg = (\n "If passing multiple notebooks with `--output=output` option, "\n "output string must contain {notebook_name}"\n )\n raise ValueError(msg)\n\n # Loop and run them one by one\n for path in self.notebooks:\n self.run_notebook(path)\n\n def get_notebooks(self) -> list[str]:\n """Get the notebooks for the app."""\n # If notebooks were provided from the command line, use those\n if self.extra_args:\n notebooks = self.extra_args\n # If not, look to the class attribute\n else:\n notebooks = self.notebooks\n\n # Return what we got.\n return notebooks\n\n def run_notebook(self, notebook_path: str) -> None:\n """Run a notebook by path."""\n # Log it\n self.log.info(f"Executing {notebook_path}")\n\n input_path = Path(notebook_path).with_suffix(".ipynb")\n\n # Get its parent directory so we can add it to the $PATH\n path = input_path.parent.absolute()\n\n # Optional output of executed notebook\n if self.inplace:\n output_path = input_path\n elif self.output_base:\n output_path = input_path.parent.joinpath(\n self.output_base.format(notebook_name=input_path.with_suffix("").name)\n ).with_suffix(".ipynb")\n else:\n output_path = None\n\n if output_path and not output_path.parent.is_dir():\n msg = f"Cannot write to directory={output_path.parent} that does not exist"\n raise ValueError(msg)\n\n # Open up the notebook we're going to run\n with input_path.open() as f:\n nb = nbformat.read(f, as_version=4)\n\n # Configure nbclient to run the notebook\n client = NotebookClient(\n nb,\n timeout=self.timeout,\n startup_timeout=self.startup_timeout,\n skip_cells_with_tag=self.skip_cells_with_tag,\n allow_errors=self.allow_errors,\n kernel_name=self.kernel_name,\n resources={"metadata": {"path": path}},\n )\n\n # Run it\n client.execute()\n\n # Save it\n if output_path:\n self.log.info(f"Save executed results to {output_path}")\n nbformat.write(nb, output_path)\n\n\nmain = NbClientApp.launch_instance\n | .venv\Lib\site-packages\nbclient\cli.py | cli.py | Python | 6,781 | 0.95 | 0.080717 | 0.07772 | node-utils | 177 | 2024-10-17T21:15:14.879569 | MIT | false | 54e7b5f32bf3589872538a8ceee86fe7 |
"""nbclient implementation."""\nfrom __future__ import annotations\n\nimport asyncio\nimport atexit\nimport base64\nimport collections\nimport datetime\nimport re\nimport signal\nimport typing as t\nfrom contextlib import asynccontextmanager, contextmanager\nfrom queue import Empty\nfrom textwrap import dedent\nfrom time import monotonic\n\nfrom jupyter_client.client import KernelClient\nfrom jupyter_client.manager import KernelManager\nfrom nbformat import NotebookNode\nfrom nbformat.v4 import output_from_msg\nfrom traitlets import Any, Bool, Callable, Dict, Enum, Integer, List, Type, Unicode, default\nfrom traitlets.config.configurable import LoggingConfigurable\n\nfrom .exceptions import (\n CellControlSignal,\n CellExecutionComplete,\n CellExecutionError,\n CellTimeoutError,\n DeadKernelError,\n)\nfrom .output_widget import OutputWidget\nfrom .util import ensure_async, run_hook, run_sync\n\n_RGX_CARRIAGERETURN = re.compile(r".*\r(?=[^\n])")\n_RGX_BACKSPACE = re.compile(r"[^\n]\b")\n\n# mypy: disable-error-code="no-untyped-call"\n\n\ndef timestamp(msg: dict[str, t.Any] | None = None) -> str:\n """Get the timestamp for a message."""\n if msg and "header" in msg: # The test mocks don't provide a header, so tolerate that\n msg_header = msg["header"]\n if "date" in msg_header and isinstance(msg_header["date"], datetime.datetime):\n try:\n # reformat datetime into expected format\n formatted_time = datetime.datetime.strftime(\n msg_header["date"], "%Y-%m-%dT%H:%M:%S.%fZ"\n )\n if (\n formatted_time\n ): # docs indicate strftime may return empty string, so let's catch that too\n return formatted_time\n except Exception: # noqa\n pass # fallback to a local time\n\n return datetime.datetime.utcnow().isoformat() + "Z"\n\n\nclass NotebookClient(LoggingConfigurable):\n """\n Encompasses a Client for executing cells in a notebook\n """\n\n timeout = Integer(\n None,\n allow_none=True,\n help=dedent(\n """\n The time to wait (in seconds) for output from executions.\n If a cell execution takes longer, a TimeoutError is raised.\n\n ``None`` or ``-1`` will disable the timeout. If ``timeout_func`` is set,\n it overrides ``timeout``.\n """\n ),\n ).tag(config=True)\n\n timeout_func: t.Callable[..., int | None] | None = Any( # type:ignore[assignment]\n default_value=None,\n allow_none=True,\n help=dedent(\n """\n A callable which, when given the cell source as input,\n returns the time to wait (in seconds) for output from cell\n executions. If a cell execution takes longer, a TimeoutError\n is raised.\n\n Returning ``None`` or ``-1`` will disable the timeout for the cell.\n Not setting ``timeout_func`` will cause the client to\n default to using the ``timeout`` trait for all cells. The\n ``timeout_func`` trait overrides ``timeout`` if it is not ``None``.\n """\n ),\n ).tag(config=True)\n\n interrupt_on_timeout = Bool(\n False,\n help=dedent(\n """\n If execution of a cell times out, interrupt the kernel and\n continue executing other cells rather than throwing an error and\n stopping.\n """\n ),\n ).tag(config=True)\n\n error_on_timeout = Dict(\n default_value=None,\n allow_none=True,\n help=dedent(\n """\n If a cell execution was interrupted after a timeout, don't wait for\n the execute_reply from the kernel (e.g. KeyboardInterrupt error).\n Instead, return an execute_reply with the given error, which should\n be of the following form::\n\n {\n 'ename': str, # Exception name, as a string\n 'evalue': str, # Exception value, as a string\n 'traceback': list(str), # traceback frames, as strings\n }\n """\n ),\n ).tag(config=True)\n\n startup_timeout = Integer(\n 60,\n help=dedent(\n """\n The time to wait (in seconds) for the kernel to start.\n If kernel startup takes longer, a RuntimeError is\n raised.\n """\n ),\n ).tag(config=True)\n\n allow_errors = Bool(\n False,\n help=dedent(\n """\n If ``False`` (default), when a cell raises an error the\n execution is stopped and a ``CellExecutionError``\n is raised, except if the error name is in\n ``allow_error_names``.\n If ``True``, execution errors are ignored and the execution\n is continued until the end of the notebook. Output from\n exceptions is included in the cell output in both cases.\n """\n ),\n ).tag(config=True)\n\n allow_error_names = List(\n Unicode(),\n help=dedent(\n """\n List of error names which won't stop the execution. Use this if the\n ``allow_errors`` option it too general and you want to allow only\n specific kinds of errors.\n """\n ),\n ).tag(config=True)\n\n force_raise_errors = Bool(\n False,\n help=dedent(\n """\n If False (default), errors from executing the notebook can be\n allowed with a ``raises-exception`` tag on a single cell, or the\n ``allow_errors`` or ``allow_error_names`` configurable options for\n all cells. An allowed error will be recorded in notebook output, and\n execution will continue. If an error occurs when it is not\n explicitly allowed, a ``CellExecutionError`` will be raised.\n If True, ``CellExecutionError`` will be raised for any error that occurs\n while executing the notebook. This overrides the ``allow_errors``\n and ``allow_error_names`` options and the ``raises-exception`` cell\n tag.\n """\n ),\n ).tag(config=True)\n\n skip_cells_with_tag = Unicode(\n "skip-execution",\n help=dedent(\n """\n Name of the cell tag to use to denote a cell that should be skipped.\n """\n ),\n ).tag(config=True)\n\n extra_arguments = List(Unicode()).tag(config=True)\n\n kernel_name = Unicode(\n "",\n help=dedent(\n """\n Name of kernel to use to execute the cells.\n If not set, use the kernel_spec embedded in the notebook.\n """\n ),\n ).tag(config=True)\n\n raise_on_iopub_timeout = Bool(\n False,\n help=dedent(\n """\n If ``False`` (default), then the kernel will continue waiting for\n iopub messages until it receives a kernel idle message, or until a\n timeout occurs, at which point the currently executing cell will be\n skipped. If ``True``, then an error will be raised after the first\n timeout. This option generally does not need to be used, but may be\n useful in contexts where there is the possibility of executing\n notebooks with memory-consuming infinite loops.\n """\n ),\n ).tag(config=True)\n\n store_widget_state = Bool(\n True,\n help=dedent(\n """\n If ``True`` (default), then the state of the Jupyter widgets created\n at the kernel will be stored in the metadata of the notebook.\n """\n ),\n ).tag(config=True)\n\n record_timing = Bool(\n True,\n help=dedent(\n """\n If ``True`` (default), then the execution timings of each cell will\n be stored in the metadata of the notebook.\n """\n ),\n ).tag(config=True)\n\n iopub_timeout = Integer(\n 4,\n allow_none=False,\n help=dedent(\n """\n The time to wait (in seconds) for IOPub output. This generally\n doesn't need to be set, but on some slow networks (such as CI\n systems) the default timeout might not be long enough to get all\n messages.\n """\n ),\n ).tag(config=True)\n\n shell_timeout_interval = Integer(\n 5,\n allow_none=False,\n help=dedent(\n """\n The time to wait (in seconds) for Shell output before retrying.\n This generally doesn't need to be set, but if one needs to check\n for dead kernels at a faster rate this can help.\n """\n ),\n ).tag(config=True)\n\n shutdown_kernel = Enum(\n ["graceful", "immediate"],\n default_value="graceful",\n help=dedent(\n """\n If ``graceful`` (default), then the kernel is given time to clean\n up after executing all cells, e.g., to execute its ``atexit`` hooks.\n If ``immediate``, then the kernel is signaled to immediately\n terminate.\n """\n ),\n ).tag(config=True)\n\n ipython_hist_file = Unicode(\n default_value=":memory:",\n help="""Path to file to use for SQLite history database for an IPython kernel.\n\n The specific value ``:memory:`` (including the colon\n at both end but not the back ticks), avoids creating a history file. Otherwise, IPython\n will create a history file for each kernel.\n\n When running kernels simultaneously (e.g. via multiprocessing) saving history a single\n SQLite file can result in database errors, so using ``:memory:`` is recommended in\n non-interactive contexts.\n """,\n ).tag(config=True)\n\n kernel_manager_class = Type(\n config=True, klass=KernelManager, help="The kernel manager class to use."\n )\n\n on_notebook_start = Callable(\n default_value=None,\n allow_none=True,\n help=dedent(\n """\n A callable which executes after the kernel manager and kernel client are setup, and\n cells are about to execute.\n Called with kwargs ``notebook``.\n """\n ),\n ).tag(config=True)\n\n on_notebook_complete = Callable(\n default_value=None,\n allow_none=True,\n help=dedent(\n """\n A callable which executes after the kernel is cleaned up.\n Called with kwargs ``notebook``.\n """\n ),\n ).tag(config=True)\n\n on_notebook_error = Callable(\n default_value=None,\n allow_none=True,\n help=dedent(\n """\n A callable which executes when the notebook encounters an error.\n Called with kwargs ``notebook``.\n """\n ),\n ).tag(config=True)\n\n on_cell_start = Callable(\n default_value=None,\n allow_none=True,\n help=dedent(\n """\n A callable which executes before a cell is executed and before non-executing cells\n are skipped.\n Called with kwargs ``cell`` and ``cell_index``.\n """\n ),\n ).tag(config=True)\n\n on_cell_execute = Callable(\n default_value=None,\n allow_none=True,\n help=dedent(\n """\n A callable which executes just before a code cell is executed.\n Called with kwargs ``cell`` and ``cell_index``.\n """\n ),\n ).tag(config=True)\n\n on_cell_complete = Callable(\n default_value=None,\n allow_none=True,\n help=dedent(\n """\n A callable which executes after a cell execution is complete. It is\n called even when a cell results in a failure.\n Called with kwargs ``cell`` and ``cell_index``.\n """\n ),\n ).tag(config=True)\n\n on_cell_executed = Callable(\n default_value=None,\n allow_none=True,\n help=dedent(\n """\n A callable which executes just after a code cell is executed, whether\n or not it results in an error.\n Called with kwargs ``cell``, ``cell_index`` and ``execute_reply``.\n """\n ),\n ).tag(config=True)\n\n on_cell_error = Callable(\n default_value=None,\n allow_none=True,\n help=dedent(\n """\n A callable which executes when a cell execution results in an error.\n This is executed even if errors are suppressed with ``cell_allows_errors``.\n Called with kwargs ``cell`, ``cell_index`` and ``execute_reply``.\n """\n ),\n ).tag(config=True)\n\n @default("kernel_manager_class")\n def _kernel_manager_class_default(self) -> type[KernelManager]:\n """Use a dynamic default to avoid importing jupyter_client at startup"""\n from jupyter_client import AsyncKernelManager # type:ignore[attr-defined]\n\n return AsyncKernelManager\n\n _display_id_map: dict[str, t.Any] = Dict( # type:ignore[assignment]\n help=dedent(\n """\n mapping of locations of outputs with a given display_id\n tracks cell index and output index within cell.outputs for\n each appearance of the display_id\n {\n 'display_id': {\n cell_idx: [output_idx,]\n }\n }\n """\n )\n )\n\n display_data_priority = List(\n [\n "text/html",\n "application/pdf",\n "text/latex",\n "image/svg+xml",\n "image/png",\n "image/jpeg",\n "text/markdown",\n "text/plain",\n ],\n help="""\n An ordered list of preferred output type, the first\n encountered will usually be used when converting discarding\n the others.\n """,\n ).tag(config=True)\n\n resources: dict[str, t.Any] = Dict( # type:ignore[assignment]\n help=dedent(\n """\n Additional resources used in the conversion process. For example,\n passing ``{'metadata': {'path': run_path}}`` sets the\n execution path to ``run_path``.\n """\n )\n )\n\n coalesce_streams = Bool(\n help=dedent(\n """\n Merge all stream outputs with shared names into single streams.\n """\n )\n )\n\n def __init__(self, nb: NotebookNode, km: KernelManager | None = None, **kw: t.Any) -> None:\n """Initializes the execution manager.\n\n Parameters\n ----------\n nb : NotebookNode\n Notebook being executed.\n km : KernelManager (optional)\n Optional kernel manager. If none is provided, a kernel manager will\n be created.\n """\n super().__init__(**kw)\n self.nb: NotebookNode = nb\n self.km: KernelManager | None = km\n self.owns_km: bool = km is None # whether the NotebookClient owns the kernel manager\n self.kc: KernelClient | None = None\n self.reset_execution_trackers()\n self.widget_registry: dict[str, dict[str, t.Any]] = {\n "@jupyter-widgets/output": {"OutputModel": OutputWidget}\n }\n # comm_open_handlers should return an object with a .handle_msg(msg) method or None\n self.comm_open_handlers: dict[str, t.Any] = {\n "jupyter.widget": self.on_comm_open_jupyter_widget\n }\n\n def reset_execution_trackers(self) -> None:\n """Resets any per-execution trackers."""\n self.task_poll_for_reply: asyncio.Future[t.Any] | None = None\n self.code_cells_executed = 0\n self._display_id_map = {}\n self.widget_state: dict[str, dict[str, t.Any]] = {}\n self.widget_buffers: dict[str, dict[tuple[str, ...], dict[str, str]]] = {}\n # maps to list of hooks, where the last is used, this is used\n # to support nested use of output widgets.\n self.output_hook_stack: t.Any = collections.defaultdict(list)\n # our front-end mimicking Output widgets\n self.comm_objects: dict[str, t.Any] = {}\n\n def create_kernel_manager(self) -> KernelManager:\n """Creates a new kernel manager.\n\n Returns\n -------\n km : KernelManager\n Kernel manager whose client class is asynchronous.\n """\n if not self.kernel_name:\n kn = self.nb.metadata.get("kernelspec", {}).get("name")\n if kn is not None:\n self.kernel_name = kn\n\n if not self.kernel_name:\n self.km = self.kernel_manager_class(config=self.config)\n else:\n self.km = self.kernel_manager_class(kernel_name=self.kernel_name, config=self.config)\n assert self.km is not None\n return self.km\n\n async def _async_cleanup_kernel(self) -> None:\n assert self.km is not None\n now = self.shutdown_kernel == "immediate"\n try:\n # Queue the manager to kill the process, and recover gracefully if it's already dead.\n if await ensure_async(self.km.is_alive()):\n await ensure_async(self.km.shutdown_kernel(now=now))\n except RuntimeError as e:\n # The error isn't specialized, so we have to check the message\n if "No kernel is running!" not in str(e):\n raise\n finally:\n # Remove any state left over even if we failed to stop the kernel\n await ensure_async(self.km.cleanup_resources())\n if getattr(self, "kc", None) and self.kc is not None:\n await ensure_async(self.kc.stop_channels()) # type:ignore[func-returns-value]\n self.kc = None\n self.km = None\n\n _cleanup_kernel = run_sync(_async_cleanup_kernel)\n\n async def async_start_new_kernel(self, **kwargs: t.Any) -> None:\n """Creates a new kernel.\n\n Parameters\n ----------\n kwargs :\n Any options for ``self.kernel_manager_class.start_kernel()``. Because\n that defaults to AsyncKernelManager, this will likely include options\n accepted by ``AsyncKernelManager.start_kernel()``, which includes ``cwd``.\n """\n assert self.km is not None\n resource_path = self.resources.get("metadata", {}).get("path") or None\n if resource_path and "cwd" not in kwargs:\n kwargs["cwd"] = resource_path\n\n has_history_manager_arg = any(\n arg.startswith("--HistoryManager.hist_file") for arg in self.extra_arguments\n )\n if (\n hasattr(self.km, "ipykernel")\n and self.km.ipykernel\n and self.ipython_hist_file\n and not has_history_manager_arg\n ):\n self.extra_arguments += [f"--HistoryManager.hist_file={self.ipython_hist_file}"]\n\n await ensure_async(self.km.start_kernel(extra_arguments=self.extra_arguments, **kwargs))\n\n start_new_kernel = run_sync(async_start_new_kernel)\n\n async def async_start_new_kernel_client(self) -> KernelClient:\n """Creates a new kernel client.\n\n Returns\n -------\n kc : KernelClient\n Kernel client as created by the kernel manager ``km``.\n """\n assert self.km is not None\n try:\n self.kc = self.km.client()\n await ensure_async(self.kc.start_channels()) # type:ignore[func-returns-value]\n await ensure_async(self.kc.wait_for_ready(timeout=self.startup_timeout))\n except Exception as e:\n self.log.error(\n "Error occurred while starting new kernel client for kernel {}: {}".format(\n getattr(self.km, "kernel_id", None), str(e)\n )\n )\n await self._async_cleanup_kernel()\n raise\n self.kc.allow_stdin = False\n await run_hook(self.on_notebook_start, notebook=self.nb)\n return self.kc\n\n start_new_kernel_client = run_sync(async_start_new_kernel_client)\n\n @contextmanager\n def setup_kernel(self, **kwargs: t.Any) -> t.Generator[None, None, None]:\n """\n Context manager for setting up the kernel to execute a notebook.\n\n The assigns the Kernel Manager (``self.km``) if missing and Kernel Client(``self.kc``).\n\n When control returns from the yield it stops the client's zmq channels, and shuts\n down the kernel.\n """\n # by default, cleanup the kernel client if we own the kernel manager\n # and keep it alive if we don't\n cleanup_kc = kwargs.pop("cleanup_kc", self.owns_km)\n\n # Can't use run_until_complete on an asynccontextmanager function :(\n if self.km is None:\n self.km = self.create_kernel_manager()\n\n if not self.km.has_kernel:\n self.start_new_kernel(**kwargs)\n\n if self.kc is None:\n self.start_new_kernel_client()\n\n try:\n yield\n finally:\n if cleanup_kc:\n self._cleanup_kernel()\n\n @asynccontextmanager\n async def async_setup_kernel(self, **kwargs: t.Any) -> t.AsyncGenerator[None, None]:\n """\n Context manager for setting up the kernel to execute a notebook.\n\n This assigns the Kernel Manager (``self.km``) if missing and Kernel Client(``self.kc``).\n\n When control returns from the yield it stops the client's zmq channels, and shuts\n down the kernel.\n\n Handlers for SIGINT and SIGTERM are also added to cleanup in case of unexpected shutdown.\n """\n # by default, cleanup the kernel client if we own the kernel manager\n # and keep it alive if we don't\n cleanup_kc = kwargs.pop("cleanup_kc", self.owns_km)\n if self.km is None:\n self.km = self.create_kernel_manager()\n\n # self._cleanup_kernel uses run_async, which ensures the ioloop is running again.\n # This is necessary as the ioloop has stopped once atexit fires.\n atexit.register(self._cleanup_kernel)\n\n def on_signal() -> None:\n """Handle signals."""\n self._async_cleanup_kernel_future = asyncio.ensure_future(self._async_cleanup_kernel())\n atexit.unregister(self._cleanup_kernel)\n\n loop = asyncio.get_event_loop()\n try:\n loop.add_signal_handler(signal.SIGINT, on_signal)\n loop.add_signal_handler(signal.SIGTERM, on_signal)\n except RuntimeError:\n # NotImplementedError: Windows does not support signals.\n # RuntimeError: Raised when add_signal_handler is called outside the main thread\n pass\n\n if not self.km.has_kernel:\n await self.async_start_new_kernel(**kwargs)\n\n if self.kc is None:\n await self.async_start_new_kernel_client()\n\n try:\n yield\n except RuntimeError as e:\n await run_hook(self.on_notebook_error, notebook=self.nb)\n raise e\n finally:\n if cleanup_kc:\n await self._async_cleanup_kernel()\n await run_hook(self.on_notebook_complete, notebook=self.nb)\n atexit.unregister(self._cleanup_kernel)\n try:\n loop.remove_signal_handler(signal.SIGINT)\n loop.remove_signal_handler(signal.SIGTERM)\n except RuntimeError:\n pass\n\n async def async_execute(self, reset_kc: bool = False, **kwargs: t.Any) -> NotebookNode:\n """\n Executes each code cell.\n\n Parameters\n ----------\n kwargs :\n Any option for ``self.kernel_manager_class.start_kernel()``. Because\n that defaults to AsyncKernelManager, this will likely include options\n accepted by ``jupyter_client.AsyncKernelManager.start_kernel()``,\n which includes ``cwd``.\n\n ``reset_kc`` if True, the kernel client will be reset and a new one\n will be created (default: False).\n\n Returns\n -------\n nb : NotebookNode\n The executed notebook.\n """\n if reset_kc and self.owns_km:\n await self._async_cleanup_kernel()\n self.reset_execution_trackers()\n\n async with self.async_setup_kernel(**kwargs):\n assert self.kc is not None\n self.log.info("Executing notebook with kernel: %s" % self.kernel_name)\n msg_id = await ensure_async(self.kc.kernel_info())\n info_msg = await self.async_wait_for_reply(msg_id)\n if info_msg is not None:\n if "language_info" in info_msg["content"]:\n self.nb.metadata["language_info"] = info_msg["content"]["language_info"]\n else:\n raise RuntimeError(\n 'Kernel info received message content has no "language_info" key. '\n "Content is:\n" + str(info_msg["content"])\n )\n for index, cell in enumerate(self.nb.cells):\n # Ignore `'execution_count' in content` as it's always 1\n # when store_history is False\n await self.async_execute_cell(\n cell, index, execution_count=self.code_cells_executed + 1\n )\n self.set_widgets_metadata()\n\n return self.nb\n\n execute = run_sync(async_execute)\n\n def set_widgets_metadata(self) -> None:\n """Set with widget metadata."""\n if self.widget_state:\n self.nb.metadata.widgets = {\n "application/vnd.jupyter.widget-state+json": {\n "state": {\n model_id: self._serialize_widget_state(state)\n for model_id, state in self.widget_state.items()\n if "_model_name" in state\n },\n "version_major": 2,\n "version_minor": 0,\n }\n }\n for key, widget in self.nb.metadata.widgets[\n "application/vnd.jupyter.widget-state+json"\n ]["state"].items():\n buffers = self.widget_buffers.get(key)\n if buffers:\n widget["buffers"] = list(buffers.values())\n\n def _update_display_id(self, display_id: str, msg: dict[str, t.Any]) -> None:\n """Update outputs with a given display_id"""\n if display_id not in self._display_id_map:\n self.log.debug("display id %r not in %s", display_id, self._display_id_map)\n return\n\n if msg["header"]["msg_type"] == "update_display_data":\n msg["header"]["msg_type"] = "display_data"\n\n try:\n out = output_from_msg(msg)\n except ValueError:\n self.log.error(f"unhandled iopub msg: {msg['msg_type']}")\n return\n\n for cell_idx, output_indices in self._display_id_map[display_id].items():\n cell = self.nb["cells"][cell_idx]\n outputs = cell["outputs"]\n for output_idx in output_indices:\n outputs[output_idx]["data"] = out["data"]\n outputs[output_idx]["metadata"] = out["metadata"]\n\n async def _async_poll_for_reply(\n self,\n msg_id: str,\n cell: NotebookNode,\n timeout: int | None,\n task_poll_output_msg: asyncio.Future[t.Any],\n task_poll_kernel_alive: asyncio.Future[t.Any],\n ) -> dict[str, t.Any]:\n msg: dict[str, t.Any]\n assert self.kc is not None\n new_timeout: float | None = None\n if timeout is not None:\n deadline = monotonic() + timeout\n new_timeout = float(timeout)\n error_on_timeout_execute_reply = None\n while True:\n try:\n if error_on_timeout_execute_reply:\n msg = error_on_timeout_execute_reply # type:ignore[unreachable]\n msg["parent_header"] = {"msg_id": msg_id}\n else:\n msg = await ensure_async(self.kc.shell_channel.get_msg(timeout=new_timeout))\n if msg["parent_header"].get("msg_id") == msg_id:\n if self.record_timing:\n cell["metadata"]["execution"]["shell.execute_reply"] = timestamp(msg)\n try:\n await asyncio.wait_for(task_poll_output_msg, self.iopub_timeout)\n except (asyncio.TimeoutError, Empty):\n if self.raise_on_iopub_timeout:\n task_poll_kernel_alive.cancel()\n raise CellTimeoutError.error_from_timeout_and_cell(\n "Timeout waiting for IOPub output", self.iopub_timeout, cell\n ) from None\n else:\n self.log.warning("Timeout waiting for IOPub output")\n task_poll_kernel_alive.cancel()\n return msg\n else:\n if new_timeout is not None:\n new_timeout = max(0, deadline - monotonic())\n except Empty:\n # received no message, check if kernel is still alive\n assert timeout is not None\n task_poll_kernel_alive.cancel()\n await self._async_check_alive()\n error_on_timeout_execute_reply = await self._async_handle_timeout(timeout, cell)\n\n async def _async_poll_output_msg(\n self, parent_msg_id: str, cell: NotebookNode, cell_index: int\n ) -> None:\n assert self.kc is not None\n while True:\n msg = await ensure_async(self.kc.iopub_channel.get_msg(timeout=None))\n if msg["parent_header"].get("msg_id") == parent_msg_id:\n try:\n # Will raise CellExecutionComplete when completed\n self.process_message(msg, cell, cell_index)\n except CellExecutionComplete:\n return\n\n async def _async_poll_kernel_alive(self) -> None:\n while True:\n await asyncio.sleep(1)\n try:\n await self._async_check_alive()\n except DeadKernelError:\n assert self.task_poll_for_reply is not None\n self.task_poll_for_reply.cancel()\n return\n\n def _get_timeout(self, cell: NotebookNode | None) -> int | None:\n if self.timeout_func is not None and cell is not None:\n timeout = self.timeout_func(cell)\n else:\n timeout = self.timeout\n\n if not timeout or timeout < 0:\n timeout = None\n\n return timeout\n\n async def _async_handle_timeout(\n self, timeout: int, cell: NotebookNode | None = None\n ) -> None | dict[str, t.Any]:\n self.log.error("Timeout waiting for execute reply (%is)." % timeout)\n if self.interrupt_on_timeout:\n self.log.error("Interrupting kernel")\n assert self.km is not None\n await ensure_async(self.km.interrupt_kernel())\n if self.error_on_timeout:\n execute_reply = {"content": {**self.error_on_timeout, "status": "error"}}\n return execute_reply\n return None\n else:\n assert cell is not None\n raise CellTimeoutError.error_from_timeout_and_cell(\n "Cell execution timed out", timeout, cell\n )\n\n async def _async_check_alive(self) -> None:\n assert self.kc is not None\n if not await ensure_async(self.kc.is_alive()): # type:ignore[attr-defined]\n self.log.error("Kernel died while waiting for execute reply.")\n raise DeadKernelError("Kernel died")\n\n async def async_wait_for_reply(\n self, msg_id: str, cell: NotebookNode | None = None\n ) -> dict[str, t.Any] | None:\n """Wait for a message reply."""\n assert self.kc is not None\n # wait for finish, with timeout\n timeout = self._get_timeout(cell)\n cummulative_time = 0\n while True:\n try:\n msg: dict[str, t.Any] = await ensure_async(\n self.kc.shell_channel.get_msg(timeout=self.shell_timeout_interval)\n )\n except Empty:\n await self._async_check_alive()\n cummulative_time += self.shell_timeout_interval\n if timeout and cummulative_time > timeout:\n await self._async_handle_timeout(timeout, cell)\n break\n else:\n if msg["parent_header"].get("msg_id") == msg_id:\n return msg\n return None\n\n wait_for_reply = run_sync(async_wait_for_reply)\n # Backwards compatibility naming for papermill\n _wait_for_reply = wait_for_reply\n\n def _passed_deadline(self, deadline: int | None) -> bool:\n if deadline is not None and deadline - monotonic() <= 0:\n return True\n return False\n\n async def _check_raise_for_error(\n self, cell: NotebookNode, cell_index: int, exec_reply: dict[str, t.Any] | None\n ) -> None:\n if exec_reply is None:\n return None\n\n exec_reply_content = exec_reply["content"]\n if exec_reply_content["status"] != "error":\n return None\n\n cell_allows_errors = (not self.force_raise_errors) and (\n self.allow_errors\n or exec_reply_content.get("ename") in self.allow_error_names\n or "raises-exception" in cell.metadata.get("tags", [])\n )\n await run_hook(\n self.on_cell_error, cell=cell, cell_index=cell_index, execute_reply=exec_reply\n )\n if not cell_allows_errors:\n raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)\n\n async def async_execute_cell(\n self,\n cell: NotebookNode,\n cell_index: int,\n execution_count: int | None = None,\n store_history: bool = True,\n ) -> NotebookNode:\n """\n Executes a single code cell.\n\n To execute all cells see :meth:`execute`.\n\n Parameters\n ----------\n cell : nbformat.NotebookNode\n The cell which is currently being processed.\n cell_index : int\n The position of the cell within the notebook object.\n execution_count : int\n The execution count to be assigned to the cell (default: Use kernel response)\n store_history : bool\n Determines if history should be stored in the kernel (default: False).\n Specific to ipython kernels, which can store command histories.\n\n Returns\n -------\n output : dict\n The execution output payload (or None for no output).\n\n Raises\n ------\n CellExecutionError\n If execution failed and should raise an exception, this will be raised\n with defaults about the failure.\n\n Returns\n -------\n cell : NotebookNode\n The cell which was just processed.\n """\n assert self.kc is not None\n\n await run_hook(self.on_cell_start, cell=cell, cell_index=cell_index)\n\n if cell.cell_type != "code" or not cell.source.strip():\n self.log.debug("Skipping non-executing cell %s", cell_index)\n return cell\n\n if self.skip_cells_with_tag in cell.metadata.get("tags", []):\n self.log.debug("Skipping tagged cell %s", cell_index)\n return cell\n\n if self.record_timing: # clear execution metadata prior to execution\n cell["metadata"]["execution"] = {}\n\n self.log.debug("Executing cell:\n%s", cell.source)\n\n cell_allows_errors = (not self.force_raise_errors) and (\n self.allow_errors or "raises-exception" in cell.metadata.get("tags", [])\n )\n\n await run_hook(self.on_cell_execute, cell=cell, cell_index=cell_index)\n parent_msg_id = await ensure_async(\n self.kc.execute(\n cell.source, store_history=store_history, stop_on_error=not cell_allows_errors\n )\n )\n await run_hook(self.on_cell_complete, cell=cell, cell_index=cell_index)\n # We launched a code cell to execute\n self.code_cells_executed += 1\n exec_timeout = self._get_timeout(cell)\n\n cell.outputs = []\n self.clear_before_next_output = False\n\n task_poll_kernel_alive = asyncio.ensure_future(self._async_poll_kernel_alive())\n task_poll_output_msg = asyncio.ensure_future(\n self._async_poll_output_msg(parent_msg_id, cell, cell_index)\n )\n self.task_poll_for_reply = asyncio.ensure_future(\n self._async_poll_for_reply(\n parent_msg_id, cell, exec_timeout, task_poll_output_msg, task_poll_kernel_alive\n )\n )\n try:\n exec_reply = await self.task_poll_for_reply\n except asyncio.CancelledError:\n # can only be cancelled by task_poll_kernel_alive when the kernel is dead\n task_poll_output_msg.cancel()\n raise DeadKernelError("Kernel died") from None\n except Exception as e:\n # Best effort to cancel request if it hasn't been resolved\n try:\n # Check if the task_poll_output is doing the raising for us\n if not isinstance(e, CellControlSignal):\n task_poll_output_msg.cancel()\n finally:\n raise\n\n if execution_count:\n cell["execution_count"] = execution_count\n await run_hook(\n self.on_cell_executed, cell=cell, cell_index=cell_index, execute_reply=exec_reply\n )\n\n if self.coalesce_streams and cell.outputs:\n new_outputs = []\n streams: dict[str, NotebookNode] = {}\n for output in cell.outputs:\n if output["output_type"] == "stream":\n if output["name"] in streams:\n streams[output["name"]]["text"] += output["text"]\n else:\n new_outputs.append(output)\n streams[output["name"]] = output\n else:\n new_outputs.append(output)\n\n # process \r and \b characters\n for output in streams.values():\n old = output["text"]\n while len(output["text"]) < len(old):\n old = output["text"]\n # Cancel out anything-but-newline followed by backspace\n output["text"] = _RGX_BACKSPACE.sub("", output["text"])\n # Replace all carriage returns not followed by newline\n output["text"] = _RGX_CARRIAGERETURN.sub("", output["text"])\n\n # We also want to ensure stdout and stderr are always in the same consecutive order,\n # because they are asynchronous, so order isn't guaranteed.\n for i, output in enumerate(new_outputs):\n if output["output_type"] == "stream" and output["name"] == "stderr":\n if (\n len(new_outputs) >= i + 2\n and new_outputs[i + 1]["output_type"] == "stream"\n and new_outputs[i + 1]["name"] == "stdout"\n ):\n stdout = new_outputs.pop(i + 1)\n new_outputs.insert(i, stdout)\n\n cell.outputs = new_outputs\n\n await self._check_raise_for_error(cell, cell_index, exec_reply)\n\n self.nb["cells"][cell_index] = cell\n return cell\n\n execute_cell = run_sync(async_execute_cell)\n\n def process_message(\n self, msg: dict[str, t.Any], cell: NotebookNode, cell_index: int\n ) -> NotebookNode | None:\n """\n Processes a kernel message, updates cell state, and returns the\n resulting output object that was appended to cell.outputs.\n\n The input argument *cell* is modified in-place.\n\n Parameters\n ----------\n msg : dict\n The kernel message being processed.\n cell : nbformat.NotebookNode\n The cell which is currently being processed.\n cell_index : int\n The position of the cell within the notebook object.\n\n Returns\n -------\n output : NotebookNode\n The execution output payload (or None for no output).\n\n Raises\n ------\n CellExecutionComplete\n Once a message arrives which indicates computation completeness.\n\n """\n msg_type = msg["msg_type"]\n self.log.debug("msg_type: %s", msg_type)\n content = msg["content"]\n self.log.debug("content: %s", content)\n\n # while it's tempting to go for a more concise\n # display_id = content.get("transient", {}).get("display_id", None)\n # this breaks if transient is explicitly set to None\n transient = content.get("transient")\n display_id = transient.get("display_id") if transient else None\n\n if display_id and msg_type in {"execute_result", "display_data", "update_display_data"}:\n self._update_display_id(display_id, msg)\n\n # set the prompt number for the input and the output\n if "execution_count" in content:\n cell["execution_count"] = content["execution_count"]\n\n if self.record_timing:\n if msg_type == "status":\n if content["execution_state"] == "idle":\n cell["metadata"]["execution"]["iopub.status.idle"] = timestamp(msg)\n elif content["execution_state"] == "busy":\n cell["metadata"]["execution"]["iopub.status.busy"] = timestamp(msg)\n elif msg_type == "execute_input":\n cell["metadata"]["execution"]["iopub.execute_input"] = timestamp(msg)\n\n if msg_type == "status":\n if content["execution_state"] == "idle":\n raise CellExecutionComplete()\n elif msg_type == "clear_output":\n self.clear_output(cell.outputs, msg, cell_index)\n elif msg_type.startswith("comm"):\n self.handle_comm_msg(cell.outputs, msg, cell_index)\n # Check for remaining messages we don't process\n elif msg_type not in ["execute_input", "update_display_data"]:\n # Assign output as our processed "result"\n return self.output(cell.outputs, msg, display_id, cell_index)\n return None\n\n def output(\n self, outs: list[NotebookNode], msg: dict[str, t.Any], display_id: str, cell_index: int\n ) -> NotebookNode | None:\n """Handle output."""\n\n msg_type = msg["msg_type"]\n out: NotebookNode | None = None\n\n parent_msg_id = msg["parent_header"].get("msg_id")\n if self.output_hook_stack[parent_msg_id]:\n # if we have a hook registered, it will override our\n # default output behaviour (e.g. OutputWidget)\n hook = self.output_hook_stack[parent_msg_id][-1]\n hook.output(outs, msg, display_id, cell_index)\n return None\n\n try:\n out = output_from_msg(msg)\n except ValueError:\n self.log.error(f"unhandled iopub msg: {msg_type}")\n return None\n\n if self.clear_before_next_output:\n self.log.debug("Executing delayed clear_output")\n outs[:] = []\n self.clear_display_id_mapping(cell_index)\n self.clear_before_next_output = False\n\n if display_id:\n # record output index in:\n # _display_id_map[display_id][cell_idx]\n cell_map = self._display_id_map.setdefault(display_id, {})\n output_idx_list = cell_map.setdefault(cell_index, [])\n output_idx_list.append(len(outs))\n\n if out:\n outs.append(out)\n\n return out\n\n def clear_output(\n self, outs: list[NotebookNode], msg: dict[str, t.Any], cell_index: int\n ) -> None:\n """Clear output."""\n content = msg["content"]\n\n parent_msg_id = msg["parent_header"].get("msg_id")\n if self.output_hook_stack[parent_msg_id]:\n # if we have a hook registered, it will override our\n # default clear_output behaviour (e.g. OutputWidget)\n hook = self.output_hook_stack[parent_msg_id][-1]\n hook.clear_output(outs, msg, cell_index)\n return\n\n if content.get("wait"):\n self.log.debug("Wait to clear output")\n self.clear_before_next_output = True\n else:\n self.log.debug("Immediate clear output")\n outs[:] = []\n self.clear_display_id_mapping(cell_index)\n\n def clear_display_id_mapping(self, cell_index: int) -> None:\n """Clear a display id mapping for a cell."""\n for _, cell_map in self._display_id_map.items():\n if cell_index in cell_map:\n cell_map[cell_index] = []\n\n def handle_comm_msg(\n self, outs: list[NotebookNode], msg: dict[str, t.Any], cell_index: int\n ) -> None:\n """Handle a comm message."""\n content = msg["content"]\n data = content["data"]\n if self.store_widget_state and "state" in data: # ignore custom msg'es\n self.widget_state.setdefault(content["comm_id"], {}).update(data["state"])\n if data.get("buffer_paths"):\n comm_id = content["comm_id"]\n if comm_id not in self.widget_buffers:\n self.widget_buffers[comm_id] = {}\n # for each comm, the path uniquely identifies a buffer\n new_buffers: dict[tuple[str, ...], dict[str, str]] = {\n tuple(k["path"]): k for k in self._get_buffer_data(msg)\n }\n self.widget_buffers[comm_id].update(new_buffers)\n # There are cases where we need to mimic a frontend, to get similar behaviour as\n # when using the Output widget from Jupyter lab/notebook\n if msg["msg_type"] == "comm_open":\n target = msg["content"].get("target_name")\n handler = self.comm_open_handlers.get(target)\n if handler:\n comm_id = msg["content"]["comm_id"]\n comm_object = handler(msg)\n if comm_object:\n self.comm_objects[comm_id] = comm_object\n else:\n self.log.warning(f"No handler found for comm target {target!r}")\n elif msg["msg_type"] == "comm_msg":\n content = msg["content"]\n comm_id = msg["content"]["comm_id"]\n if comm_id in self.comm_objects:\n self.comm_objects[comm_id].handle_msg(msg)\n\n def _serialize_widget_state(self, state: dict[str, t.Any]) -> dict[str, t.Any]:\n """Serialize a widget state, following format in @jupyter-widgets/schema."""\n return {\n "model_name": state.get("_model_name"),\n "model_module": state.get("_model_module"),\n "model_module_version": state.get("_model_module_version"),\n "state": state,\n }\n\n def _get_buffer_data(self, msg: dict[str, t.Any]) -> list[dict[str, str]]:\n encoded_buffers = []\n paths = msg["content"]["data"]["buffer_paths"]\n buffers = msg["buffers"]\n for path, buffer in zip(paths, buffers):\n encoded_buffers.append(\n {\n "data": base64.b64encode(buffer).decode("utf-8"),\n "encoding": "base64",\n "path": path,\n }\n )\n return encoded_buffers\n\n def register_output_hook(self, msg_id: str, hook: OutputWidget) -> None:\n """Registers an override object that handles output/clear_output instead.\n\n Multiple hooks can be registered, where the last one will be used (stack based)\n """\n # mimics\n # https://jupyterlab.github.io/jupyterlab/services/interfaces/kernel.ikernelconnection.html#registermessagehook\n self.output_hook_stack[msg_id].append(hook)\n\n def remove_output_hook(self, msg_id: str, hook: OutputWidget) -> None:\n """Unregisters an override object that handles output/clear_output instead"""\n # mimics\n # https://jupyterlab.github.io/jupyterlab/services/interfaces/kernel.ikernelconnection.html#removemessagehook\n removed_hook = self.output_hook_stack[msg_id].pop()\n assert removed_hook == hook\n\n def on_comm_open_jupyter_widget(self, msg: dict[str, t.Any]) -> t.Any | None:\n """Handle a jupyter widget comm open."""\n content = msg["content"]\n data = content["data"]\n state = data["state"]\n comm_id = msg["content"]["comm_id"]\n module = self.widget_registry.get(state["_model_module"])\n if module:\n widget_class = module.get(state["_model_name"])\n if widget_class:\n return widget_class(comm_id, state, self.kc, self)\n return None\n\n\ndef execute(\n nb: NotebookNode,\n cwd: str | None = None,\n km: KernelManager | None = None,\n **kwargs: t.Any,\n) -> NotebookNode:\n """Execute a notebook's code, updating outputs within the notebook object.\n\n This is a convenient wrapper around NotebookClient. It returns the\n modified notebook object.\n\n Parameters\n ----------\n nb : NotebookNode\n The notebook object to be executed\n cwd : str, optional\n If supplied, the kernel will run in this directory\n km : AsyncKernelManager, optional\n If supplied, the specified kernel manager will be used for code execution.\n kwargs :\n Any other options for NotebookClient, e.g. timeout, kernel_name\n """\n resources = {}\n if cwd is not None:\n resources["metadata"] = {"path": cwd}\n return NotebookClient(nb=nb, resources=resources, km=km, **kwargs).execute()\n | .venv\Lib\site-packages\nbclient\client.py | client.py | Python | 49,833 | 0.95 | 0.166793 | 0.045887 | awesome-app | 51 | 2023-09-26T15:58:53.374661 | Apache-2.0 | false | 1dc2284e06d7b9cb0967ee493c790a38 |
"""Exceptions for nbclient."""\nfrom __future__ import annotations\n\nfrom typing import Any\n\nfrom nbformat import NotebookNode\n\n\nclass CellControlSignal(Exception): # noqa\n """\n A custom exception used to indicate that the exception is used for cell\n control actions (not the best model, but it's needed to cover existing\n behavior without major refactors).\n """\n\n pass\n\n\nclass CellTimeoutError(TimeoutError, CellControlSignal):\n """\n A custom exception to capture when a cell has timed out during execution.\n """\n\n @classmethod\n def error_from_timeout_and_cell(\n cls, msg: str, timeout: int, cell: NotebookNode\n ) -> CellTimeoutError:\n """Create an error from a timeout on a cell."""\n if cell and cell.source:\n src_by_lines = cell.source.strip().split("\n")\n src = (\n cell.source\n if len(src_by_lines) < 11\n else f"{src_by_lines[:5]}\n...\n{src_by_lines[-5:]}"\n )\n else:\n src = "Cell contents not found."\n return cls(timeout_err_msg.format(timeout=timeout, msg=msg, cell_contents=src))\n\n\nclass DeadKernelError(RuntimeError):\n """A dead kernel error."""\n\n pass\n\n\nclass CellExecutionComplete(CellControlSignal):\n """\n Used as a control signal for cell execution across execute_cell and\n process_message function calls. Raised when all execution requests\n are completed and no further messages are expected from the kernel\n over zeromq channels.\n """\n\n pass\n\n\nclass CellExecutionError(CellControlSignal):\n """\n Custom exception to propagate exceptions that are raised during\n notebook execution to the caller. This is mostly useful when\n using nbconvert as a library, since it allows to deal with\n failures gracefully.\n """\n\n def __init__(self, traceback: str, ename: str, evalue: str) -> None:\n """Initialize the error."""\n super().__init__(traceback)\n self.traceback = traceback\n self.ename = ename\n self.evalue = evalue\n\n def __reduce__(self) -> tuple[Any]:\n """Reduce implementation."""\n return type(self), (self.traceback, self.ename, self.evalue) # type:ignore[return-value]\n\n def __str__(self) -> str:\n """Str repr."""\n if self.traceback:\n return self.traceback\n else:\n return f"{self.ename}: {self.evalue}"\n\n @classmethod\n def from_cell_and_msg(cls, cell: NotebookNode, msg: dict[str, Any]) -> CellExecutionError:\n """Instantiate from a code cell object and a message contents\n (message is either execute_reply or error)\n """\n\n # collect stream outputs for our error message\n stream_outputs: list[str] = []\n for output in cell.outputs:\n if output["output_type"] == "stream":\n stream_outputs.append(\n stream_output_msg.format(name=output["name"], text=output["text"].rstrip())\n )\n if stream_outputs:\n # add blank line before, trailing separator\n # if there is any stream output to display\n stream_outputs.insert(0, "")\n stream_outputs.append("------------------")\n stream_output: str = "\n".join(stream_outputs)\n\n tb = "\n".join(msg.get("traceback", []) or [])\n return cls(\n exec_err_msg.format(\n cell=cell,\n stream_output=stream_output,\n traceback=tb,\n ),\n ename=msg.get("ename", "<Error>"),\n evalue=msg.get("evalue", ""),\n )\n\n\nstream_output_msg: str = """\\n----- {name} -----\n{text}"""\n\nexec_err_msg: str = """\\nAn error occurred while executing the following cell:\n------------------\n{cell.source}\n------------------\n{stream_output}\n\n{traceback}\n"""\n\n\ntimeout_err_msg: str = """\\nA cell timed out while it was being executed, after {timeout} seconds.\nThe message was: {msg}.\nHere is a preview of the cell contents:\n-------------------\n{cell_contents}\n-------------------\n"""\n | .venv\Lib\site-packages\nbclient\exceptions.py | exceptions.py | Python | 4,065 | 0.95 | 0.173913 | 0.027273 | react-lib | 529 | 2024-04-03T22:09:44.324099 | GPL-3.0 | false | 6a6670110e504a6cd3092e14dc6ec43d |
"""Utilities to manipulate JSON objects."""\n\n# NOTE: this is a copy of ipykernel/jsonutils.py (+blackified)\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport math\nimport numbers\nimport re\nimport types\nfrom binascii import b2a_base64\nfrom datetime import datetime\nfrom typing import Any\n\n# -----------------------------------------------------------------------------\n# Globals and constants\n# -----------------------------------------------------------------------------\n\n# timestamp formats\nISO8601 = "%Y-%m-%dT%H:%M:%S.%f"\nISO8601_PAT = re.compile(\n r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(\.\d{1,6})?Z?([\+\-]\d{2}:?\d{2})?$"\n)\n\n# holy crap, strptime is not threadsafe.\n# Calling it once at import seems to help.\ndatetime.strptime("2000-01-01", "%Y-%m-%d")\n\n# -----------------------------------------------------------------------------\n# Classes and functions\n# -----------------------------------------------------------------------------\n\n\n# constants for identifying png/jpeg data\nPNG = b"\x89PNG\r\n\x1a\n"\n# front of PNG base64-encoded\nPNG64 = b"iVBORw0KG"\nJPEG = b"\xff\xd8"\n# front of JPEG base64-encoded\nJPEG64 = b"/9"\n# constants for identifying gif data\nGIF_64 = b"R0lGODdh"\nGIF89_64 = b"R0lGODlh"\n# front of PDF base64-encoded\nPDF64 = b"JVBER"\n\n\ndef encode_images(format_dict: dict[str, str]) -> dict[str, str]:\n """b64-encodes images in a displaypub format dict\n\n Perhaps this should be handled in json_clean itself?\n\n Parameters\n ----------\n\n format_dict : dict\n A dictionary of display data keyed by mime-type\n\n Returns\n -------\n\n format_dict : dict\n A copy of the same dictionary,\n but binary image data ('image/png', 'image/jpeg' or 'application/pdf')\n is base64-encoded.\n\n """\n return format_dict\n\n\ndef json_clean(obj: Any) -> Any:\n """Clean an object to ensure it's safe to encode in JSON.\n\n Atomic, immutable objects are returned unmodified. Sets and tuples are\n converted to lists, lists are copied and dicts are also copied.\n\n Note: dicts whose keys could cause collisions upon encoding (such as a dict\n with both the number 1 and the string '1' as keys) will cause a ValueError\n to be raised.\n\n Parameters\n ----------\n obj : any python object\n\n Returns\n -------\n out : object\n\n A version of the input which will not cause an encoding error when\n encoded as JSON. Note that this function does not *encode* its inputs,\n it simply sanitizes it so that there will be no encoding errors later.\n\n """\n # types that are 'atomic' and ok in json as-is.\n atomic_ok = (str, type(None))\n\n # containers that we need to convert into lists\n container_to_list = (tuple, set, types.GeneratorType)\n\n # Since bools are a subtype of Integrals, which are a subtype of Reals,\n # we have to check them in that order.\n\n if isinstance(obj, bool):\n return obj\n\n if isinstance(obj, numbers.Integral):\n # cast int to int, in case subclasses override __str__ (e.g. boost enum, #4598)\n return int(obj)\n\n if isinstance(obj, numbers.Real):\n # cast out-of-range floats to their reprs\n if math.isnan(obj) or math.isinf(obj):\n return repr(obj)\n return float(obj)\n\n if isinstance(obj, atomic_ok):\n return obj\n\n if isinstance(obj, bytes):\n return b2a_base64(obj).decode("ascii")\n\n if isinstance(obj, container_to_list) or (\n hasattr(obj, "__iter__") and hasattr(obj, "__next__")\n ):\n obj = list(obj)\n\n if isinstance(obj, list):\n return [json_clean(x) for x in obj]\n\n if isinstance(obj, dict):\n # First, validate that the dict won't lose data in conversion due to\n # key collisions after stringification. This can happen with keys like\n # True and 'true' or 1 and '1', which collide in JSON.\n nkeys = len(obj)\n nkeys_collapsed = len(set(map(str, obj)))\n if nkeys != nkeys_collapsed:\n raise ValueError(\n "dict cannot be safely converted to JSON: "\n "key collision would lead to dropped values"\n )\n # If all OK, proceed by making the new dict that will be json-safe\n out = {}\n for k, v in iter(obj.items()):\n out[str(k)] = json_clean(v)\n return out\n if isinstance(obj, datetime):\n return obj.strftime(ISO8601)\n\n # we don't understand it, it's probably an unserializable object\n raise ValueError("Can't clean for JSON: %r" % obj)\n | .venv\Lib\site-packages\nbclient\jsonutil.py | jsonutil.py | Python | 4,612 | 0.95 | 0.125 | 0.241379 | awesome-app | 469 | 2025-03-14T17:44:38.894636 | Apache-2.0 | false | e720cd474f3c1eedca8d44aa14161144 |
"""An output widget mimic."""\nfrom __future__ import annotations\n\nfrom typing import Any\n\nfrom jupyter_client.client import KernelClient\nfrom nbformat import NotebookNode\nfrom nbformat.v4 import output_from_msg\n\nfrom .jsonutil import json_clean\n\n\nclass OutputWidget:\n """This class mimics a front end output widget"""\n\n def __init__(\n self, comm_id: str, state: dict[str, Any], kernel_client: KernelClient, executor: Any\n ) -> None:\n """Initialize the widget."""\n self.comm_id: str = comm_id\n self.state: dict[str, Any] = state\n self.kernel_client: KernelClient = kernel_client\n self.executor = executor\n self.topic: bytes = ("comm-%s" % self.comm_id).encode("ascii")\n self.outputs: list[NotebookNode] = self.state["outputs"]\n self.clear_before_next_output: bool = False\n\n def clear_output(self, outs: list[NotebookNode], msg: dict[str, Any], cell_index: int) -> None:\n """Clear output."""\n self.parent_header = msg["parent_header"]\n content = msg["content"]\n if content.get("wait"):\n self.clear_before_next_output = True\n else:\n self.outputs = []\n # sync back the state to the kernel\n self.sync_state()\n if hasattr(self.executor, "widget_state"):\n # sync the state to the nbconvert state as well, since that is used for testing\n self.executor.widget_state[self.comm_id]["outputs"] = self.outputs\n\n def sync_state(self) -> None:\n """Sync state."""\n state = {"outputs": self.outputs}\n msg = {"method": "update", "state": state, "buffer_paths": []}\n self.send(msg)\n\n def _publish_msg(\n self,\n msg_type: str,\n data: dict[str, Any] | None = None,\n metadata: dict[str, Any] | None = None,\n buffers: list[Any] | None = None,\n **keys: Any,\n ) -> None:\n """Helper for sending a comm message on IOPub"""\n data = {} if data is None else data\n metadata = {} if metadata is None else metadata\n content = json_clean(dict(data=data, comm_id=self.comm_id, **keys))\n msg = self.kernel_client.session.msg(\n msg_type, content=content, parent=self.parent_header, metadata=metadata\n )\n self.kernel_client.shell_channel.send(msg)\n\n def send(\n self,\n data: dict[str, Any] | None = None,\n metadata: dict[str, Any] | None = None,\n buffers: list[Any] | None = None,\n ) -> None:\n """Send a comm message."""\n self._publish_msg("comm_msg", data=data, metadata=metadata, buffers=buffers)\n\n def output(\n self, outs: list[NotebookNode], msg: dict[str, Any], display_id: str, cell_index: int\n ) -> None:\n """Handle output."""\n if self.clear_before_next_output:\n self.outputs = []\n self.clear_before_next_output = False\n self.parent_header = msg["parent_header"]\n output = output_from_msg(msg) # type:ignore[no-untyped-call]\n\n if self.outputs:\n # try to coalesce/merge output text\n last_output = self.outputs[-1]\n if (\n last_output["output_type"] == "stream"\n and output["output_type"] == "stream"\n and last_output["name"] == output["name"]\n ):\n last_output["text"] += output["text"]\n else:\n self.outputs.append(output)\n else:\n self.outputs.append(output)\n self.sync_state()\n if hasattr(self.executor, "widget_state"):\n # sync the state to the nbconvert state as well, since that is used for testing\n self.executor.widget_state[self.comm_id]["outputs"] = self.outputs\n\n def set_state(self, state: dict[str, Any]) -> None:\n """Set the state."""\n if "msg_id" in state:\n msg_id = state.get("msg_id")\n if msg_id:\n self.executor.register_output_hook(msg_id, self)\n self.msg_id = msg_id\n else:\n self.executor.remove_output_hook(self.msg_id, self)\n self.msg_id = msg_id\n\n def handle_msg(self, msg: dict[str, Any]) -> None:\n """Handle a message."""\n content = msg["content"]\n comm_id = content["comm_id"]\n if comm_id != self.comm_id:\n raise AssertionError("Mismatched comm id")\n data = content["data"]\n if "state" in data:\n self.set_state(data["state"])\n | .venv\Lib\site-packages\nbclient\output_widget.py | output_widget.py | Python | 4,527 | 0.95 | 0.214876 | 0.046729 | vue-tools | 52 | 2024-07-14T08:21:47.671685 | BSD-3-Clause | false | eac7e157081e8c9141d704c86f31b803 |
"""General utility methods"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport inspect\nfrom typing import Any, Callable\n\nfrom jupyter_core.utils import ensure_async, run_sync\n\n__all__ = ["ensure_async", "run_sync", "run_hook"]\n\n\nasync def run_hook(hook: Callable[..., Any] | None, **kwargs: Any) -> None:\n """Run a hook callback."""\n if hook is None:\n return\n res = hook(**kwargs)\n if inspect.isawaitable(res):\n await res\n | .venv\Lib\site-packages\nbclient\util.py | util.py | Python | 544 | 0.95 | 0.142857 | 0.133333 | awesome-app | 900 | 2024-07-14T03:50:47.241514 | MIT | false | addd8a739550136052665938753ff98a |
"""Version info."""\nfrom __future__ import annotations\n\nimport re\n\n__version__ = "0.10.2"\n\n# Build up version_info tuple for backwards compatibility\npattern = r"(?P<major>\d+).(?P<minor>\d+).(?P<patch>\d+)(?P<rest>.*)"\nmatch = re.match(pattern, __version__)\nif match:\n parts: list[int | str] = [int(match[part]) for part in ["major", "minor", "patch"]]\n if match["rest"]:\n parts.append(match["rest"])\nelse:\n parts = []\nversion_info = tuple(parts)\n | .venv\Lib\site-packages\nbclient\_version.py | _version.py | Python | 463 | 0.95 | 0.235294 | 0.071429 | react-lib | 819 | 2024-11-06T00:38:45.045564 | GPL-3.0 | false | d3264deb324706306173414dae75f12b |
from ._version import __version__, version_info\nfrom .client import NotebookClient, execute\n\n__all__ = ["__version__", "version_info", "NotebookClient", "execute"]\n | .venv\Lib\site-packages\nbclient\__init__.py | __init__.py | Python | 164 | 0.85 | 0 | 0 | awesome-app | 448 | 2023-10-11T09:03:46.338346 | MIT | false | 72ba4d5052eeea9603ad6cb5457c1aef |
\n\n | .venv\Lib\site-packages\nbclient\__pycache__\cli.cpython-313.pyc | cli.cpython-313.pyc | Other | 7,902 | 0.8 | 0.032 | 0 | react-lib | 259 | 2024-03-31T14:57:21.525042 | MIT | false | 13451eef6c7ac4123bbd1546be38559d |
\n\n | .venv\Lib\site-packages\nbclient\__pycache__\client.cpython-313.pyc | client.cpython-313.pyc | Other | 56,348 | 0.75 | 0.066852 | 0.004471 | node-utils | 954 | 2024-08-29T17:16:57.817023 | BSD-3-Clause | false | aab30308b7e8465e0e639362ec398804 |
\n\n | .venv\Lib\site-packages\nbclient\__pycache__\exceptions.cpython-313.pyc | exceptions.cpython-313.pyc | Other | 5,928 | 0.95 | 0.071429 | 0 | react-lib | 305 | 2025-03-10T19:19:37.197783 | BSD-3-Clause | false | 1721d89925e69498f915f78a2d0a3276 |
\n\n | .venv\Lib\site-packages\nbclient\__pycache__\jsonutil.cpython-313.pyc | jsonutil.cpython-313.pyc | Other | 4,349 | 0.95 | 0.025974 | 0 | node-utils | 897 | 2025-01-15T20:29:54.655640 | MIT | false | ec6fd48984669d40ea0ac7bb27f1fe5d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.