
    -Ph                    	   U d dl mZ d dlZd dlZd dlmZ d dlmZmZ d dl	m
Z
 d dlmZ d dlmZmZ d dlmZ d d	lmZmZmZmZmZmZmZmZmZmZmZmZmZm Z  d d
l!m"Z" d dl#m$Z$ d dl%m&Z& d dl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z> d dl?m@Z@mAZAmBZB erd dlCmDZD d dlmEZF d dlGZHd dlIZJd dlKZLd dlMmNZNmOZOmPZPmQZQmRZRmSZS d dlTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[ d dl\m]Z] d dl^m_Z_m`Z` d dlambZbmcZcmdZd d dlemfZfmgZg d dlhmiZi d dljmkZk d dllmmZmmnZnmoZompZpmqZqmrZrmsZsmtZtmuZumvZvmwZwmxZxmyZymzZzm{Z{m|Z|  edeege         efe         eke         f                   Z} ed          Z~ ed          Z ed          Z edd           Z ePd!          Z ed"          Z ed#          Z ed$          Z G d% d&e          Z G d' d(e          Z G d) d*e          Z G d+ d,e          Z G d- d.e          Z G d/ d0eee          Z G d1 d2eee          Z G d3 d4e          Z ed5          Z ed6d78          Z ed9d78          Z ed:d2          Zd;Zd<ed=<   d>Zd<ed?<    G d@ dAee                   Z G dB dCee                   Z G dD dEe          Z G dF dGe$          Zej        dHej        dHej        dIej        dJej        dKej        dKej        dLej        dMej        dNej        dOej        dPiZdQedR<   d5dXZd6d\Zd7d^Zd8dbZd9ddZd:dgZd;djZe d<dp            Ze d=ds            Ze d>dv            Ze d?dx            Ze d@d{            Ze dAd}            Ze dBd            ZdCdZdDdZdEdZdFdZ	 dGdddHdZdIdZdJdZdKdZdLdZdMdZdNdZdOdZdOdZdPdZdQdZdRdZdSdZdTdZdUdZdVdZdWdZdXdZdYdńZdZdƄZÐd[dǄZĐd\dʄZŐd]dτZdddҜd^dքZǐd_dۄZȐd`dބZɐdadZʐdbdZːdcdZ̐dddZ͐dedZΐdfdZϐdgdZАdhdZѐdidZҐdjdZӐdkdZԐdkdZՐdldZ֐dmdZאdnd
ZؐdodZِdpdZڐdqdZېdrdZܐdsdZݐdtdZ G d d          Zߐdud!Z G d" d#          Zdvd'Zdwd+Zdxd-ZdАd.dyd2Z G d3 d4ee                   ZdS (z      )annotationsN)timezone)Enumautowraps)	find_spec)getattr_staticgetdoc)	token_hex)TYPE_CHECKINGAnyCallable	ContainerGenericIterableIteratorLiteralProtocolSequenceTypeVarUnioncastoverload)warn)
NoAutoEnum
deprecated)get_cudfget_daskget_dask_dataframe
get_duckdbget_ibis	get_modin
get_pandas
get_polarsget_pyarrowget_pysparkget_pyspark_connectget_pyspark_sqlget_sqlframeis_narwhals_seriesis_narwhals_series_intis_numpy_array_1dis_numpy_array_1d_intis_pandas_dataframeis_pandas_like_dataframeis_pandas_like_seriesis_pandas_seriesis_polars_seriesis_pyarrow_chunked_array)ColumnNotFoundErrorDuplicateErrorInvalidOperationError)
ModuleType)AbstractSet)ConcatenateLiteralString	ParamSpecSelf	TypeAliasTypeIs)CompliantExprCompliantExprTCompliantFrameTCompliantSeriesOrNativeExprT_coCompliantSeriesTNativeFrameT_coNativeSeriesT_co)	EvalNames)EagerAllowedImplementation	Namespace)ArrowStreamExportableIntoArrowTableToNarwhalsT_co	DataFrame	LazyFrameDTypeSeries)CompliantDataFrameCompliantLazyFrameCompliantSeriesDataFrameLikeDTypesIntoSeriesTMultiIndexSelectorSingleIndexSelectorSizedMultiIndexSelectorSizeUnitSupportsNativeNamespaceTimeUnit_1DArray_SliceIndex
_SliceName
_SliceNoneFrameOrSeriesT)bound_T1_T2_T3_FnzCallable[..., Any]PRR1R2c                      e Zd ZU ded<   dS )_SupportsVersionstr__version__N__name__
__module____qualname____annotations__     O/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/narwhals/_utils.pyrp   rp   y   s         ry   rp   c                      e Zd Zdd	dZdS )
_SupportsGetNinstancer   owner
Any | Nonereturnc                   d S Nrx   )selfr}   r~   s      rz   __get__z_SupportsGet.__get__}   s      ry   r   )r}   r   r~   r   r   r   )rt   ru   rv   r   rx   ry   rz   r|   r|   |   s        QQQQQQQry   r|   c                      e Zd ZU ded<   dS )_StoresImplementationImplementation_implementationNrs   rx   ry   rz   r   r      s         ''''MMry   r   c                      e Zd ZU ded<   dS )_StoresBackendVersiontuple[int, ...]_backend_versionNrs   rx   ry   rz   r   r      s         ))))11ry   r   c                      e Zd ZU ded<   dS )_StoresVersionVersion_versionNrs   rx   ry   rz   r   r      s         00ry   r   c                      e Zd ZdZdS )_LimitedContextzRProvides 2 attributes.

        - `_backend_version`
        - `_version`
        Nrt   ru   rv   __doc__rx   ry   rz   r   r      s        	 	 	 	ry   r   c                      e Zd ZdZdS )_FullContextznProvides 3 attributes.

        - `_implementation`
        - `_backend_version`
        - `_version`
        Nr   rx   ry   rz   r   r      s        	 	 	 	ry   r   c                  &    e Zd Zedd            ZdS )_StoresColumnsr   Sequence[str]c                    d S r   rx   r   s    rz   columnsz_StoresColumns.columns   s    ,/Cry   N)r   r   )rt   ru   rv   propertyr   rx   ry   rz   r   r      s&        	/// 
///ry   r   _T
NativeT_coT)	covariantCompliantT_co	_ContextTz&Callable[Concatenate[_ContextT, P], R]r?   _Methodz Callable[Concatenate[_T, P], R2]_Constructorc                  *    e Zd ZdZedd            ZdS )_StoresNativezProvides access to a native object.

    Native objects have types like:

    >>> from pandas import Series
    >>> from pyarrow import Table
    r   r   c                    dS )zReturn the native object.Nrx   r   s    rz   nativez_StoresNative.native   	     	ry   N)r   r   )rt   ru   rv   r   r   r   rx   ry   rz   r   r      >             X  ry   r   c                  *    e Zd ZdZedd            ZdS )_StoresCompliantzProvides access to a compliant object.

    Compliant objects have types like:

    >>> from narwhals._pandas_like.series import PandasLikeSeries
    >>> from narwhals._arrow.dataframe import ArrowDataFrame
    r   r   c                    dS )zReturn the compliant object.Nrx   r   s    rz   	compliantz_StoresCompliant.compliant   r   ry   N)r   r   )rt   ru   rv   r   r   r   rx   ry   rz   r   r      r   ry   r   c                      e Zd Z e            Z e            Zedd            Zedd            Zedd            Z	edd	            Z
edd            ZdS )r   r   type[Namespace[Any]]c                >    | t           j        u rddlm} |S ddlm} |S )Nr   )rJ   )r   MAINnarwhals._namespacerJ   narwhals.stable.v1._namespace)r   rJ   s     rz   	namespacezVersion.namespace   s?    7<555555;;;;;;ry   rY   c                >    | t           j        u rddlm} |S ddlm} |S )Nr   )dtypes)r   r   narwhalsr   narwhals.stable.v1)r   r   	v1_dtypess      rz   r   zVersion.dtypes   s>    7<''''''M::::::ry   type[DataFrame[Any]]c                >    | t           j        u rddlm} |S ddlm} |S )Nr   )rO   )r   r   narwhals.dataframerO   r   )r   rO   DataFrameV1s      rz   	dataframezVersion.dataframe   ?    7<444444??????ry   type[LazyFrame[Any]]c                >    | t           j        u rddlm} |S ddlm} |S )Nr   )rP   )r   r   r   rP   r   )r   rP   LazyFrameV1s      rz   	lazyframezVersion.lazyframe   r   ry   type[Series[Any]]c                >    | t           j        u rddlm} |S ddlm} |S )Nr   rS   )r   r   narwhals.seriesrT   r   )r   rT   SeriesV1s      rz   serieszVersion.series   s=    7<......M999999ry   N)r   r   )r   rY   )r   r   )r   r   )r   r   )rt   ru   rv   r   V1r   r   r   r   r   r   r   rx   ry   rz   r   r      s        	B466D   X    X    X    X    X  ry   r   c                  "   e Zd ZdZdZ	 dZ	 dZ	 dZ	 dZ	 dZ		 dZ
	 d	Z	 d
Z	 dZ	 dZ	 dZ	 d-dZed.d            Zed/d            Zed0d            Zd1dZd2dZd2dZd2dZd2d Zd2d!Zd2d"Zd2d#Zd2d$Zd2d%Zd2d&Zd2d'Z d2d(Z!d2d)Z"d3d+Z#d,S )4r   z?Implementation of native object (pandas, Polars, PyArrow, ...).pandasmodincudfpyarrowpysparkpolarsdaskduckdbibissqlframezpyspark[connect]unknownr   rq   c                *    t          | j                  S r   )rq   valuer   s    rz   __str__zImplementation.__str__  s    4:ry   cls
type[Self]native_namespacer9   c                V   t                      t          j        t                      t          j        t                      t          j        t                      t          j        t                      t          j
        t                      t          j        t                      t          j        t                      t          j        t#                      t          j        t'                      t          j        t+                      t          j        i}|                    |t          j                  S )zInstantiate Implementation object from a native namespace module.

        Arguments:
            native_namespace: Native namespace.

        Returns:
            Implementation.
        )r%   r   PANDASr$   MODINr   CUDFr'   PYARROWr*   PYSPARKr&   POLARSr!   DASKr"   DUCKDBr#   IBISr+   SQLFRAMEr)   PYSPARK_CONNECTgetUNKNOWN)r   r   mappings      rz   from_native_namespacez$Implementation.from_native_namespace  s     LL./KK-JJ+MM>1~5LL./  ."5LL./JJ+NNN3!!>#A
 {{+^-CDDDry   backend_namec                R    	  | |          S # t           $ r t          j        cY S w xY w)zInstantiate Implementation object from a native namespace module.

        Arguments:
            backend_name: Name of backend, expressed as string.

        Returns:
            Implementation.
        )
ValueErrorr   r   )r   r   s     rz   from_stringzImplementation.from_string6  sA    	*3|$$$ 	* 	* 	*!))))	*s   
 &&backend!str | Implementation | ModuleTypec                    t          |t                    r|                     |          n+t          |t                    r|n|                     |          S )zInstantiate from native namespace module, string, or Implementation.

        Arguments:
            backend: Backend to instantiate Implementation from.

        Returns:
            Implementation.
        )
isinstancerq   r   r   r   )r   r   s     rz   from_backendzImplementation.from_backendG  sU     '3''4COOG$$$ '>224**733	
ry   c                   | t           j        u rddl}|S | t           j        u rddl}|j        S | t           j        u rddl}|S | t           j        u rddl}|S | t           j	        u rddl
}|j        S | t           j        u rddl}|S | t           j        u rddl}|j        S | t           j        u rddl}|S | t           j        u rddl}	|	S | t           j        u rddl}
|
S | t           j        u rddl}|j        j        S d}t5          |          )zyReturn the native namespace module corresponding to Implementation.

        Returns:
            Native module.
        r   NzNot supported Implementation)r   r   r   r   modin.pandasr   r   r   r   r   pyspark.sqlsqlr   r   r   dask.dataframer   r   r   r   r   r   r   r   pyspark.sql.connectconnectAssertionError)r   pdr   r   par   plr   r   r   r   msgs               rz   to_native_namespacez"Implementation.to_native_namespace[  so    >(((I>'''<>&&&KKKK>)))    I>)));>(((I>&&&!!!!>!>(((MMMM>***OOOO>&&&KKKK>111&&&&;&&,S!!!ry   boolc                    | t           j        u S )a^  Return whether implementation is pandas.

        Returns:
            Boolean.

        Examples:
            >>> import pandas as pd
            >>> import narwhals as nw
            >>> df_native = pd.DataFrame({"a": [1, 2, 3]})
            >>> df = nw.from_native(df_native)
            >>> df.implementation.is_pandas()
            True
        )r   r   r   s    rz   	is_pandaszImplementation.is_pandas       ~,,,ry   c                L    | t           j        t           j        t           j        hv S )as  Return whether implementation is pandas, Modin, or cuDF.

        Returns:
            Boolean.

        Examples:
            >>> import pandas as pd
            >>> import narwhals as nw
            >>> df_native = pd.DataFrame({"a": [1, 2, 3]})
            >>> df = nw.from_native(df_native)
            >>> df.implementation.is_pandas_like()
            True
        )r   r   r   r   r   s    rz   is_pandas_likezImplementation.is_pandas_like  s     -~/C^EXYYYry   c                L    | t           j        t           j        t           j        hv S )ap  Return whether implementation is pyspark or sqlframe.

        Returns:
            Boolean.

        Examples:
            >>> import pandas as pd
            >>> import narwhals as nw
            >>> df_native = pd.DataFrame({"a": [1, 2, 3]})
            >>> df = nw.from_native(df_native)
            >>> df.implementation.is_spark_like()
            False
        )r   r   r   r   r   s    rz   is_spark_likezImplementation.is_spark_like  s(     "#*
 
 	
ry   c                    | t           j        u S )a^  Return whether implementation is Polars.

        Returns:
            Boolean.

        Examples:
            >>> import polars as pl
            >>> import narwhals as nw
            >>> df_native = pl.DataFrame({"a": [1, 2, 3]})
            >>> df = nw.from_native(df_native)
            >>> df.implementation.is_polars()
            True
        )r   r   r   s    rz   	is_polarszImplementation.is_polars  r  ry   c                    | t           j        u S )a[  Return whether implementation is cuDF.

        Returns:
            Boolean.

        Examples:
            >>> import polars as pl
            >>> import narwhals as nw
            >>> df_native = pl.DataFrame({"a": [1, 2, 3]})
            >>> df = nw.from_native(df_native)
            >>> df.implementation.is_cudf()
            False
        )r   r   r   s    rz   is_cudfzImplementation.is_cudf       ~***ry   c                    | t           j        u S )a]  Return whether implementation is Modin.

        Returns:
            Boolean.

        Examples:
            >>> import polars as pl
            >>> import narwhals as nw
            >>> df_native = pl.DataFrame({"a": [1, 2, 3]})
            >>> df = nw.from_native(df_native)
            >>> df.implementation.is_modin()
            False
        )r   r   r   s    rz   is_modinzImplementation.is_modin  s     ~+++ry   c                    | t           j        u S )aa  Return whether implementation is PySpark.

        Returns:
            Boolean.

        Examples:
            >>> import polars as pl
            >>> import narwhals as nw
            >>> df_native = pl.DataFrame({"a": [1, 2, 3]})
            >>> df = nw.from_native(df_native)
            >>> df.implementation.is_pyspark()
            False
        )r   r   r   s    rz   
is_pysparkzImplementation.is_pyspark       ~---ry   c                    | t           j        u S )ai  Return whether implementation is PySpark.

        Returns:
            Boolean.

        Examples:
            >>> import polars as pl
            >>> import narwhals as nw
            >>> df_native = pl.DataFrame({"a": [1, 2, 3]})
            >>> df = nw.from_native(df_native)
            >>> df.implementation.is_pyspark_connect()
            False
        )r   r   r   s    rz   is_pyspark_connectz!Implementation.is_pyspark_connect	  s     ~555ry   c                    | t           j        u S )aa  Return whether implementation is PyArrow.

        Returns:
            Boolean.

        Examples:
            >>> import polars as pl
            >>> import narwhals as nw
            >>> df_native = pl.DataFrame({"a": [1, 2, 3]})
            >>> df = nw.from_native(df_native)
            >>> df.implementation.is_pyarrow()
            False
        )r   r   r   s    rz   
is_pyarrowzImplementation.is_pyarrow  r  ry   c                    | t           j        u S )a[  Return whether implementation is Dask.

        Returns:
            Boolean.

        Examples:
            >>> import polars as pl
            >>> import narwhals as nw
            >>> df_native = pl.DataFrame({"a": [1, 2, 3]})
            >>> df = nw.from_native(df_native)
            >>> df.implementation.is_dask()
            False
        )r   r   r   s    rz   is_daskzImplementation.is_dask)  r  ry   c                    | t           j        u S )a_  Return whether implementation is DuckDB.

        Returns:
            Boolean.

        Examples:
            >>> import polars as pl
            >>> import narwhals as nw
            >>> df_native = pl.DataFrame({"a": [1, 2, 3]})
            >>> df = nw.from_native(df_native)
            >>> df.implementation.is_duckdb()
            False
        )r   r   r   s    rz   	is_duckdbzImplementation.is_duckdb9  r  ry   c                    | t           j        u S )a[  Return whether implementation is Ibis.

        Returns:
            Boolean.

        Examples:
            >>> import polars as pl
            >>> import narwhals as nw
            >>> df_native = pl.DataFrame({"a": [1, 2, 3]})
            >>> df = nw.from_native(df_native)
            >>> df.implementation.is_ibis()
            False
        )r   r   r   s    rz   is_ibiszImplementation.is_ibisI  r  ry   c                    | t           j        u S )ac  Return whether implementation is SQLFrame.

        Returns:
            Boolean.

        Examples:
            >>> import polars as pl
            >>> import narwhals as nw
            >>> df_native = pl.DataFrame({"a": [1, 2, 3]})
            >>> df = nw.from_native(df_native)
            >>> df.implementation.is_sqlframe()
            False
        )r   r   r   s    rz   is_sqlframezImplementation.is_sqlframeY  s     ~...ry   r   c                P   |                                  }| t          j        t          j        t          j        t          j        hvr|}nQ| t          j        t          j        hv rt                      }n(| t          j        u rt                      }ndd l}|j	        }t          |          S Nr   )r  r   r   r   r   r   r(   r    sqlframe._versionr   parse_version)r   r   into_versionr   s       rz   r   zImplementation._backend_versioni  s    ))++"*#	
 
 
 "LLn,n.LMMM&==LL^(((#::LL$$$$#,L\***ry   Nr   rq   )r   r   r   r9   r   r   )r   r   r   rq   r   r   )r   r   r   r   r   r   )r   r9   )r   r  )r   r   )$rt   ru   rv   r   r   r   r   r   r   r   r   r   r   r   r   r   r   classmethodr   r   r   r  r  r  r
  r  r  r  r  r  r  r  r  r  r   r   rx   ry   rz   r   r      s#       IIF EDG!G!F DF DH"(O)G!    E E E [E4 * * * [*  
 
 
 [
&8" 8" 8" 8"t- - - - Z Z Z Z 
 
 
 
(- - - - + + + + , , , , . . . . 6 6 6 6 . . . . + + + + - - - - + + + + / / / / + + + + + +ry   r   )r         )   
   )   )r)     )r      r)  )i        )   )r)     r   z%dict[Implementation, tuple[int, ...]]MIN_VERSIONSimplementationbackend_versionr   r   Nonec                `    |t           |          x}k     rd|  d| d| }t          |          d S )NzMinimum version of z supported by Narwhals is z	, found: )r4  r   )r5  r6  min_versionr  s       rz   validate_backend_versionr:    sL     n)EE+FFuNuukuudsuuoo GFry   textrq   prefixc                ^    |                      |          r| t          |          d          S | S r   )
startswithlen)r;  r<  s     rz   remove_prefixr@    s0    v #CKKMM""Kry   suffixc                `    |                      |          r| d t          |                    S | S r   )endswithr?  )r;  rA  s     rz   remove_suffixrD    s2    }}V $Ns6{{lN##Kry   argsr   	list[Any]c                    t          t          |           dk    rt          | d                   r| d         n|           S )Nr1  r   )listr?  _is_iterable)rE  s    rz   flattenrJ    s6    CIINN|DG/D/DNQ4PPPry   argc                D    t          | t          t          f          s| fS | S r   )r   rH  tuple)rK  s    rz   tupleifyrN    s$    cD%=)) vJry   Any | Iterable[Any]r  c                   ddl m} t          |           st          |           r"dt	          |           d}t          |          t                      x}Jt          | |j        |j        |j	        |j
        f          r"dt	          |           d}t          |          t          | t                    ot          | t          t          |f           S )Nr   rS   z(Expected Narwhals class or scalar, got: z2. Perhaps you forgot a `nw.from_native` somewhere?z`.

Hint: Perhaps you
- forgot a `nw.from_native` somewhere?
- used `pl.col` instead of `nw.col`?)r   rT   r0   r3   qualified_type_name	TypeErrorr&   r   ExprrO   rP   r   rq   bytes)rK  rT   r  r   s       rz   rI  rI    s    &&&&&&3 #3C#8#8  H9LS9Q9Q  H  H  Hnnll'Jbi",=- -'37J37O7O 3 3 3 	 nnc8$$RZc5&=Q-R-R)RRry   version#str | ModuleType | _SupportsVersionc                    t          | t                    r| n| j        }t          j        dd|          }t          d |                    d          D                       S )zSimple version parser; split into a tuple of ints for comparison.

    Arguments:
        version: Version string, or object with one, to parse.

    Returns:
        Parsed version number.
    z(\D?dev.*$) c              3  \   K   | ]'}t          t          j        d d|                    V  (dS )z\DrX  N)intresub).0vs     rz   	<genexpr>z parse_version.<locals>.<genexpr>  s8      KKqRVE2q))**KKKKKKry   .)r   rq   rr   r[  r\  rM  split)rU  version_strs     rz   r$  r$    s]     (55N''7;NK&[99KKKK4E4Ec4J4JKKKKKKry   
obj_or_clstypecls_or_tupletype[_T]TypeIs[type[_T]]c                    d S r   rx   rc  re  s     rz   isinstance_or_issubclassrj    s	     sry   object | typeTypeIs[_T | type[_T]]c                    d S r   rx   ri  s     rz   rj  rj    s	      Cry   tuple[type[_T1], type[_T2]]TypeIs[type[_T1 | _T2]]c                    d S r   rx   ri  s     rz   rj  rj    s	     "cry   #TypeIs[_T1 | _T2 | type[_T1 | _T2]]c                    d S r   rx   ri  s     rz   rj  rj    s	     +.#ry   &tuple[type[_T1], type[_T2], type[_T3]]TypeIs[type[_T1 | _T2 | _T3]]c                    d S r   rx   ri  s     rz   rj  rj    s	     %(Cry   /TypeIs[_T1 | _T2 | _T3 | type[_T1 | _T2 | _T3]]c                    d S r   rx   ri  s     rz   rj  rj    s	     7:cry   tuple[type, ...]TypeIs[Any]c                    d S r   rx   ri  s     rz   rj  rj    s	     #ry   c                    ddl m} t          | |          rt          | |          S t          | |          p$t          | t                    ot	          | |          S )Nr   rQ   )narwhals.dtypesrR   r   rd  
issubclass)rc  re  rR   s      rz   rj  rj    si    %%%%%%*e$$ 4*l333j,// :t$$MJ)M)Mry   itemsIterable[Any]c                    ddl mm t          fd| D                       st          fd| D                       rd S dd | D              }t	          |          )Nr   rN   c              3  8   K   | ]}t          |          V  d S r   r   )r]  itemrO   s     rz   r_  z$validate_laziness.<locals>.<genexpr>  s-      
9
94:dI&&
9
9
9
9
9
9ry   c              3  8   K   | ]}t          |          V  d S r   r  )r]  r  rP   s     rz   r_  z$validate_laziness.<locals>.<genexpr>  s-      ::DJtY''::::::ry   zGThe items to concatenate should either all be eager, or all lazy, got: c                ,    g | ]}t          |          S rx   )rd  )r]  r  s     rz   
<listcomp>z%validate_laziness.<locals>.<listcomp>  s#    TrTrTrdhUYZ^U_U_TrTrTrry   )r   rO   rP   allrR  )r~  r  rO   rP   s     @@rz   validate_lazinessr    s    77777777

9
9
9
95
9
9
999 ::::E::::: 	
tTrTrlqTrTrTr
t
tC
C..ry   lhsrhs-Series[Any] | DataFrame[Any] | LazyFrame[Any]c                    ddl m} ddlm} dd}t	          d|           }t	          d|          }t          t          |d	d
          |          rt          t          |d	d
          |          r ||j        j        j	                    ||j        j        j	                   |
                    |j                            |j        j        j        |j        j        j	                                     S t          t          |d	d
          |          rt          t          |dd
          |          r ||j        j        j	                    ||j        j        j	                   |
                    |j                            |j        j        j        |j        j        j	                                     S t          t          |dd
          |          rt          t          |d	d
          |          r ||j        j        j	                    ||j        j        j	                   |
                    |j                            |j        j        j        |j        j        j	                                     S t          t          |dd
          |          rt          t          |dd
          |          r ||j        j        j	                    ||j        j        j	                   |
                    |j                            |j        j        j        |j        j        j	                                     S t          |          t          |          k    r1dt          |           dt          |           }t          |          | S )a  Align `lhs` to the Index of `rhs`, if they're both pandas-like.

    Arguments:
        lhs: Dataframe or Series.
        rhs: Dataframe or Series to align with.

    Returns:
        Same type as input.

    Notes:
        This is only really intended for backwards-compatibility purposes,
        for example if your library already aligns indices for users.
        If you're designing a new library, we highly encourage you to not
        rely on the Index.
        For non-pandas-like inputs, this only checks that `lhs` and `rhs`
        are the same length.

    Examples:
        >>> import pandas as pd
        >>> import polars as pl
        >>> import narwhals as nw
        >>> df_pd = pd.DataFrame({"a": [1, 2]}, index=[3, 4])
        >>> s_pd = pd.Series([6, 7], index=[4, 3])
        >>> df = nw.from_native(df_pd)
        >>> s = nw.from_native(s_pd, series_only=True)
        >>> nw.to_native(nw.maybe_align_index(df, s))
           a
        4  2
        3  1
    r   )PandasLikeDataFrame)PandasLikeSeriesindexr   r   r7  c                6    | j         sd}t          |          d S )Nz'given index doesn't have a unique index)	is_uniquer   )r  r  s     rz   _validate_indexz*maybe_align_index.<locals>._validate_index3  s'     	";CS//!	" 	"ry   _compliant_frameN_compliant_seriesz6Expected `lhs` and `rhs` to have the same length, got z and )r  r   r   r7  )narwhals._pandas_like.dataframer  narwhals._pandas_like.seriesr  r   r   getattrr  r   r  _with_compliant_with_nativelocr  r?  r   )r  r  r  r  r  lhs_anyrhs_anyr  s           rz   maybe_align_indexr    s   B DCCCCC======" " " "
 5#G5#G+T224G  	

WW&8$??AT
U
U	
 	07=>>>07=>>>&&$11(/3G4L4S4YZ 
 
 	

 +T224G  

WW&94@@BR
S
S
 	07=>>>18>???&&$11(/3-4: 
 
 	
 ,d335E  

WW&8$??AT
U
U
 	18>???07=>>>&&%22)04,39 
 
 	
 ,d335E  

WW&94@@BR
S
S
 	18>???18>???&&%22)04-4: 
 
 	
 7||s7||##hs7||hhZ]^eZfZfhhooJry   obj-DataFrame[Any] | LazyFrame[Any] | Series[Any]r   c                    t          d|           }|                                }t          |          st          |          r|j        S dS )a  Get the index of a DataFrame or a Series, if it's pandas-like.

    Arguments:
        obj: Dataframe or Series.

    Returns:
        Same type as input.

    Notes:
        This is only really intended for backwards-compatibility purposes,
        for example if your library already aligns indices for users.
        If you're designing a new library, we highly encourage you to not
        rely on the Index.
        For non-pandas-like inputs, this returns `None`.

    Examples:
        >>> import pandas as pd
        >>> import polars as pl
        >>> import narwhals as nw
        >>> df_pd = pd.DataFrame({"a": [1, 2], "b": [4, 5]})
        >>> df = nw.from_native(df_pd)
        >>> nw.maybe_get_index(df)
        RangeIndex(start=0, stop=2, step=1)
        >>> series_pd = pd.Series([1, 2])
        >>> series = nw.from_native(series_pd, series_only=True)
        >>> nw.maybe_get_index(series)
        RangeIndex(start=0, stop=2, step=1)
    r   N)r   	to_nativer1   r2   r  )r  obj_any
native_objs      rz   maybe_get_indexr  n  sR    : 5#G""$$J
++  /DZ/P/P  4ry   )r  column_namesstr | list[str] | Noner  6Series[IntoSeriesT] | list[Series[IntoSeriesT]] | Nonec                  ddl m t          d|           }|                                }||d}t          |          |s|d}t          |          |+t	          |          rfd|D             n |d	          }n|}t          |          r@|                    |j                            |	                    |                              S t          |          ridd
lm	} |rd}t          |           |||| j        j        | j        j                  }|                    |j                            |                    S |S )a  Set the index of a DataFrame or a Series, if it's pandas-like.

    Arguments:
        obj: object for which maybe set the index (can be either a Narwhals `DataFrame`
            or `Series`).
        column_names: name or list of names of the columns to set as index.
            For dataframes, only one of `column_names` and `index` can be specified but
            not both. If `column_names` is passed and `df` is a Series, then a
            `ValueError` is raised.
        index: series or list of series to set as index.

    Returns:
        Same type as input.

    Raises:
        ValueError: If one of the following conditions happens

            - none of `column_names` and `index` are provided
            - both `column_names` and `index` are provided
            - `column_names` is provided and `df` is a Series

    Notes:
        This is only really intended for backwards-compatibility purposes, for example if
        your library already aligns indices for users.
        If you're designing a new library, we highly encourage you to not
        rely on the Index.

        For non-pandas-like inputs, this is a no-op.

    Examples:
        >>> import pandas as pd
        >>> import polars as pl
        >>> import narwhals as nw
        >>> df_pd = pd.DataFrame({"a": [1, 2], "b": [4, 5]})
        >>> df = nw.from_native(df_pd)
        >>> nw.to_native(nw.maybe_set_index(df, "b"))  # doctest: +NORMALIZE_WHITESPACE
           a
        b
        4  1
        5  2
    r   )r  r   Nz8Only one of `column_names` or `index` should be providedz3Either `column_names` or `index` should be providedc                *    g | ]} |d           S )Tpass_throughrx   )r]  idxr  s     rz   r  z#maybe_set_index.<locals>.<listcomp>  s(    @@@3YYs...@@@ry   Tr  )	set_indexz/Cannot set index using column names on a Series)r5  r6  )narwhals.translater  r   r   rI  r1   r  r  r  r  r2   narwhals._pandas_like.utilsr  r   r   )	r  r  r  df_anyr  r  keysr  r  s	           @rz   maybe_set_indexr    s   ^ -,,,,,%F!!##JE$5Hoo EMCoo E""5@@@@%@@@@5t444 	 
++ %%#001E1Ed1K1KLL
 
 	
 
z	*	* 999999 	"CCS//!Y0@1B	
 
 

 %%f&>&K&KJ&W&WXXXry   c                &   t          d|           }|                                }t          |          rg|                                }t	          ||          r|S |                    |j                            |                    d                              S t          |          rg|                                }t	          ||          r|S |                    |j
                            |                    d                              S |S )a  Reset the index to the default integer index of a DataFrame or a Series, if it's pandas-like.

    Arguments:
        obj: Dataframe or Series.

    Returns:
        Same type as input.

    Notes:
        This is only really intended for backwards-compatibility purposes,
        for example if your library already resets the index for users.
        If you're designing a new library, we highly encourage you to not
        rely on the Index.
        For non-pandas-like inputs, this is a no-op.

    Examples:
        >>> import pandas as pd
        >>> import polars as pl
        >>> import narwhals as nw
        >>> df_pd = pd.DataFrame({"a": [1, 2], "b": [4, 5]}, index=([6, 7]))
        >>> df = nw.from_native(df_pd)
        >>> nw.to_native(nw.maybe_reset_index(df))
           a  b
        0  1  4
        1  2  5
        >>> series_pd = pd.Series([1, 2])
        >>> series = nw.from_native(series_pd, series_only=True)
        >>> nw.maybe_get_index(series)
        RangeIndex(start=0, stop=2, step=1)
    r   T)drop)r   r  r1   __native_namespace___has_default_indexr  r  r  reset_indexr2   r  )r  r  r  r   s       rz   maybe_reset_indexr    s   > 5#G""$$J
++ 
"7799j*:;; 	N&&$11*2H2Hd2H2S2STT
 
 	
 Z(( 
"7799j*:;; 	N&&%22:3I3It3I3T3TUU
 
 	
 Nry   r   TypeIs[pd.RangeIndex]c                ,    t          | |j                  S r   )r   
RangeIndex)r  r   s     rz   _is_range_indexr    s    c+6777ry   native_frame_or_seriespd.Series[Any] | pd.DataFramec                    | j         }t          ||          o-|j        dk    o"|j        t	          |          k    o
|j        dk    S )Nr   r1  )r  r  startstopr?  step)r  r   r  s      rz   r  r  #  sS     #(E/00 	K1	J#e**$	 J!O	ry   kwargs
bool | strc           	     j   t          d|           }|                                }t          |          r8|                    |j                             |j        |i |                    S t          |          r8|                    |j                             |j        |i |                    S |S )aW  Convert columns or series to the best possible dtypes using dtypes supporting ``pd.NA``, if df is pandas-like.

    Arguments:
        obj: DataFrame or Series.
        *args: Additional arguments which gets passed through.
        **kwargs: Additional arguments which gets passed through.

    Returns:
        Same type as input.

    Notes:
        For non-pandas-like inputs, this is a no-op.
        Also, `args` and `kwargs` just get passed down to the underlying library as-is.

    Examples:
        >>> import pandas as pd
        >>> import polars as pl
        >>> import narwhals as nw
        >>> import numpy as np
        >>> df_pd = pd.DataFrame(
        ...     {
        ...         "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),
        ...         "b": pd.Series([True, False, np.nan], dtype=np.dtype("O")),
        ...     }
        ... )
        >>> df = nw.from_native(df_pd)
        >>> nw.to_native(
        ...     nw.maybe_convert_dtypes(df)
        ... ).dtypes  # doctest: +NORMALIZE_WHITESPACE
        a             Int32
        b           boolean
        dtype: object
    r   )	r   r  r1   r  r  r  convert_dtypesr2   r  )r  rE  r  r  r  s        rz   maybe_convert_dtypesr  /  s    H 5#G""$$J
++ 
&&$11)
)4:6:: 
 
 	

 Z(( 
&&%22)
)4:6:: 
 
 	

 Nry   szrZ  unitr^   int | floatc                ~    |dv r| S |dv r| dz  S |dv r| dz  S |dv r| dz  S |dv r| d	z  S d
|}t          |          )zScale size in bytes to other size units (eg: "kb", "mb", "gb", "tb").

    Arguments:
        sz: original size in bytes
        unit: size unit to convert into

    Returns:
        Integer or float.
    >   brT  >   kb	kilobytesi   >   mb	megabytesi   >   gb	gigabytesi   @>   tb	terabytesl        z9`unit` must be one of {'b', 'kb', 'mb', 'gb', 'tb'}, got )r   )r  r  r  s      rz   scale_bytesr  d  s     ~		$	$	$Dy	$	$	$G|	$	$	$G|	$	$	$G|TDTToory   r   Series[Any]c                D   ddl m} | j        j        j        }| j        }d}t          ||          r-t          | j        |j                  r|j        j	        d         }n| j        |j
        k    rd}n| j        |j        k    rd}n|                                 }t          |          rt          d|j                  j        dk    }nZt          |          rt!          |j        j                  }n1t'          |          r"ddlm}  ||j                  o|j        j        }|S )	a  Return whether indices of categories are semantically meaningful.

    This is a convenience function to accessing what would otherwise be
    the `is_ordered` property from the DataFrame Interchange Protocol,
    see https://data-apis.org/dataframe-protocol/latest/API.html.

    - For Polars:
      - Enums are always ordered.
      - Categoricals are ordered if `dtype.ordering == "physical"`.
    - For pandas-like APIs:
      - Categoricals are ordered if `dtype.cat.ordered == True`.
    - For PyArrow table:
      - Categoricals are ordered if `dtype.type.ordered == True`.

    Arguments:
        series: Input Series.

    Returns:
        Whether the Series is an ordered categorical.

    Examples:
        >>> import narwhals as nw
        >>> import pandas as pd
        >>> import polars as pl
        >>> data = ["x", "y"]
        >>> s_pd = pd.Series(data, dtype=pd.CategoricalDtype(ordered=True))
        >>> s_pl = pl.Series(data, dtype=pl.Categorical(ordering="physical"))

        Let's define a library-agnostic function:

        >>> @nw.narwhalify
        ... def func(s):
        ...     return nw.is_ordered_categorical(s)

        Then, we can pass any supported library to `func`:

        >>> func(s_pd)
        True
        >>> func(s_pl)
        True
    r   )InterchangeSeriesF
is_orderedTzpl.Categoricalphysical)is_dictionary)narwhals._interchange.seriesr  r  r   r   r   dtypeCategoricalr   describe_categoricalr   r  r4   r   orderingr2   r  catorderedr5   narwhals._arrow.utilsr  rd  )r   r  r   r   resultr   r  s          rz   is_ordered_categoricalr  }  sI   T ?>>>>>%.5F(IF).// HJf(5 5 H !6|D		$	$	+	+	+!!##F## 	H*FL99BjPFF"6** 	H&*,--FF%f-- 	H;;;;;;"]6;//GFK4GFMry   n_bytesr   r   c                J    d}t          |d           t          | |          S )Nz}Use `generate_temporary_column_name` instead. `generate_unique_token` is deprecated and it will be removed in future versions1.13.0r   )r  r   )issue_deprecation_warninggenerate_temporary_column_name)r  r   r  s      rz   generate_unique_tokenr    s4    	?  cH5555)'7KKKKry   c                x    d}	 t          |           }||vr|S |dz  }|dk    rd| d| }t          |          8)a  Generates a unique column name that is not present in the given list of columns.

    It relies on [python secrets token_hex](https://docs.python.org/3/library/secrets.html#secrets.token_hex)
    function to return a string nbytes random bytes.

    Arguments:
        n_bytes: The number of bytes to generate for the token.
        columns: The list of columns to check for uniqueness.

    Returns:
        A unique token that is not present in the given list of columns.

    Raises:
        AssertionError: If a unique token cannot be generated after 100 attempts.

    Examples:
        >>> import narwhals as nw
        >>> columns = ["abc", "xyz"]
        >>> nw.generate_temporary_column_name(n_bytes=8, columns=columns) not in columns
        True
    r   Tr1  d   zMInternal Error: Narwhals was not able to generate a column name with n_bytes=z and not in )r   r   )r  r   countertokenr  s        rz   r  r    sv    , G&'""L1S==33 3)03 3  !%%%&ry   framesubsetIterable[str]strict	list[str]c                  |s4t          t          | j                                      |                    S t          |          }t	          || j                  x}r||S )N)	available)rH  setr   intersectioncheck_columns_exist)r  r  r  to_droperrors        rz   parse_columns_to_dropr    sc      =C&&33F;;<<<6llG#Gu}EEEEu Nry   sequenceSequence[_T] | AnyTypeIs[Sequence[_T]]c                X    t          | t                    ot          | t                     S r   )r   r   rq   )r  s    rz   is_sequence_but_not_strr    s$    h))K*Xs2K2K.KKry   TypeIs[_SliceNone]c                R    t          | t                    o| t          d           k    S r   )r   slicer  s    rz   is_slice_noner    s"    c5!!8cU4[[&88ry   CTypeIs[SizedMultiIndexSelector[Series[Any] | CompliantSeries[Any]]]c                    t          |           o@t          |           dk    rt          | d         t                    pt          |           dk    p,t	          |           pt          |           pt          |           S r"  )r  r?  r   rZ  r/   r-   is_compliant_series_intr  s    rz   is_sized_multi_index_selectorr    s    
 $C(( Pc((Q,::c!fc#:#:NCA	( !%%		(
 "#&&	( #3''ry   -TypeIs[Sequence[_T] | Series[Any] | _1DArray]c                z    t          |           p,t          |           pt          |           pt          |           S r   )r  r.   r,   is_compliant_seriesr  s    rz   is_sequence_liker    sF     	 $$ 	$S!!	$c""	$ s##	ry   TypeIs[_SliceIndex]c                    t          | t                    o_t          | j        t                    pEt          | j        t                    p+t          | j        t                    o| j        d u o| j        d u S r   )r   r  r  rZ  r  r  r  s    rz   is_slice_indexr    sj    c5!! 39c"" 	Rch$$	Rsx%%P#)t*;PD@Pry   TypeIs[range]c                ,    t          | t                    S r   )r   ranger  s    rz   is_ranger  &  s    c5!!!ry   TypeIs[SingleIndexSelector]c                r    t          t          | t                    ot          | t                                S r   )r  r   rZ  r  s    rz   is_single_index_selectorr  *  s,    
3$$BZT-B-B)BCCCry   TTypeIs[SingleIndexSelector | MultiIndexSelector[Series[Any] | CompliantSeries[Any]]]c                \    t          |           pt          |           pt          |           S r   )r  r  r  r  s    rz   is_index_selectorr  .  s4     	!%% 	(--	#ry   tpTypeIs[list[_T]]c                v    t          t          | t                    o| ot          | d         |                    S r"  )r  r   rH  )r  r  s     rz   
is_list_ofr   8  s2    
3%%H#H*SVR2H2HIIIry   c                    t          t          |           o.t          t          |           d           x}ot	          ||                    S r   )r  r  nextiterr   )r  r  firsts      rz   is_sequence_ofr%  =  sN    $$ 	"499d+++U	"ub!!  ry   c                 x   ddl } ddlm} ddl}t	           ||j                  j                  }|                                 }d}	 |rg|                     |          }|	                    |          s-t          |j        dd          x}r"|	                    d          r|j        }|dz  }nn|g	 ~n# ~w xY w|S )zFind the first place in the stack that is not inside narwhals.

    Returns:
        Stacklevel.

    Taken from:
    https://github.com/pandas-dev/pandas/blob/ab89c53f48df67709a533b6a95ce3d911871a0a8/pandas/util/_exceptions.py#L30-L51
    r   N)Pathco_qualnamezsingledispatch.r1  )inspectpathlibr'  r   rq   __file__parentcurrentframegetfiler>  r  f_codef_back)r)  r'  nwpkg_dirr  nfnamequalnames           rz   find_stacklevelr6  F  s    NNN$$r{##*++G   ""E	A 	OOE**E(( $U\=$GGG ''(9::
 Q  	  EE				Hs   A*B4 4B7messager   c                L    t          | t          t                                 dS )zIssue a deprecation warning.

    Arguments:
        message: The message associated with the warning.
        _version: Narwhals version when the warning was introduced. Just used for internal
            bookkeeping.
    )r7  category
stacklevelN)r   DeprecationWarningr6  )r7  r   s     rz   r  r  p  s&     	#5/BSBSTTTTTTry   bool | Noner  pass_through_defaultemit_deprecation_warningc               z    | ||}n3| ||rd}t          |d           |  }n| |nd}t          |          |S )Nz`strict` in `from_native` is deprecated, please use `pass_through` instead.

Note: `strict` will remain available in `narwhals.stable.v1`.
See https://narwhals-dev.github.io/narwhals/backcompat/ for more information.
r  r  z,Cannot pass both `strict` and `pass_through`)r  r   )r  r  r=  r>  r  s        rz   validate_strict_and_pass_thoughr@  {  su     ~,.+		 4# 	>b 
 &cH====!z	L4<oory   rX  F)warn_versionrequiredrA  rB  *Callable[[Callable[P, R]], Callable[P, R]]c                     d fd}|S )a8  Decorator to transition from `native_namespace` to `backend` argument.

    Arguments:
        warn_version: Emit a deprecation warning from this version.
        required: Raise when both `native_namespace`, `backend` are `None`.

    Returns:
        Wrapped function, with `native_namespace` **removed**.
    fnCallable[P, R]r   c               D     t                     d fd            }|S )	NrE  P.argskwdsP.kwargsr   rl   c                    |                     dd           }|                     dd           }||rd}t          |           |}n5||d}t          |          ||rdj         d}t          |          ||d<    | i |S )Nr   r   z`native_namespace` is deprecated, please use `backend` instead.

Note: `native_namespace` will remain available in `narwhals.stable.v1`.
See https://narwhals-dev.github.io/narwhals/backcompat/ for more information.
r  z0Can't pass both `native_namespace` and `backend`z `backend` must be specified in `z`.)popr  r   rt   )rE  rI  r   r   r  rE  rB  rA  s        rz   wrapperz=deprecate_native_namespace.<locals>.decorate.<locals>.wrapper  s    hhy$//G#xx(:DAA+ Jj 
 .cLIIII*!-'2EH oo%!)go(oHHHH oo%%DO2t$t$$$ry   )rE  rH  rI  rJ  r   rl   r   )rE  rM  rB  rA  s   ` rz   decoratez,deprecate_native_namespace.<locals>.decorate  sC    	r	% 	% 	% 	% 	% 	% 	% 
	%* ry   )rE  rF  r   rF  rx   )rA  rB  rN  s   `` rz   deprecate_native_namespacerO    s.          2 Ory   window_sizemin_samples
int | Nonetuple[int, int]c                   t          | t          d           t          |t          t          d           d           | dk     rd}t          |          |/|dk     rd}t          |          || k    rd}t	          |          n| }| |fS )NrP  
param_namerQ  r1  z+window_size must be greater or equal than 1z+min_samples must be greater or equal than 1z6`min_samples` must be less or equal than `window_size`)ensure_typerZ  rd  r   r8   )rP  rQ  r  s      rz   _validate_rolling_argumentsrX    s     S];;;;S$t**GGGGQ;oo???CS//!$$JC',,, % "##ry   headernative_reprc           
        	 t          j                    j        }n2# t          $ r% t	          t          j        dd                    }Y nw xY w|                                                                }t          d |D                       }|dz   |k    rt          |t          |                     }dd|z   d}|t          |           z
  }|dd	|dz  z   |  d	|dz  |dz  z   z   d
z  }|dd|z   d
z  }||z
  dz  }||z
  dz  ||z
  dz  z   }	|D ](}
|dd	|z   |
 d	|	|z   t          |
          z
  z   d
z  })|dd|z   dz  }|S dt          |           z
  }dd dd	|dz  z   |  d	|dz  |dz  z   z   dd d	S )NCOLUMNSP   c              3  4   K   | ]}t          |          V  d S r   )r?  )r]  lines     rz   r_  z generate_repr.<locals>.<genexpr>  s(      >>3t99>>>>>>ry      u   ┌u   ─u   ┐
| z|
-u   └u   ┘'   uu   ───────────────────────────────────────u   ┐
|u/   |
| Use `.to_native` to see native output |
└)
osget_terminal_sizer   OSErrorrZ  getenv
expandtabs
splitlinesmaxr?  )rY  rZ  terminal_widthnative_linesmax_native_widthlengthoutputheader_extrastart_extra	end_extrar_  diffs               rz   generate_reprru    sE   7-//7 7 7 7RYy"55667))++6688L>>>>>>>!~--%s6{{33,uv~,,,F+jc\Q./jjPQ@QT`cdTd@d9ejjjj)cVn)))) 00Q6..14AQ8QUV7VV	  	k 	kDj#-jtjSIHX<X[^_c[d[d<d5ejjjjFF+++++FD	l 	 	419	%	'*dai$(.B'C	 	 	 	 	s    ,A
	A
r  ColumnNotFoundError | Nonec              x    t          |                               |          x}rt          j        ||          S d S r   )r  
differencer6   'from_missing_and_available_column_names)r  r  missings      rz   r  r    sF     f++((333w 
"JY
 
 	
 4ry   c                L   t          t          |                     }t          |           |k    rtddlm}  ||           }d |                                D             }d                    d |                                D                       }d| }t          |          d S )Nr   )Counterc                &    i | ]\  }}|d k    ||S r0  rx   r]  kr^  s      rz   
<dictcomp>z1check_column_names_are_unique.<locals>.<dictcomp>  s#    @@@tq!!a%%a%%%ry   rX  c              3  .   K   | ]\  }}d | d| dV  dS )z
- 'z' z timesNrx   r~  s      rz   r_  z0check_column_names_are_unique.<locals>.<genexpr>  s:      LLA,a,,1,,,LLLLLLry   z"Expected unique column names, got:)r?  r  collectionsr|  r~  joinr7   )r   len_unique_columnsr|  r  
duplicatesr  s         rz   check_column_names_are_uniquer    s    S\\**
7||)))''''''''""@@w}}@@@
ggLL9I9I9K9KLLLLL8388S!!! *)ry   	time_unit$TimeUnit | Iterable[TimeUnit] | None	time_zone7str | timezone | Iterable[str | timezone | None] | None%tuple[Set[TimeUnit], Set[str | None]]c                    | h dn&t          | t                    r| hnt          |           }|d hn7t          |t          t          f          rt          |          hnd |D             }||fS )N>   smsnsusc                4    h | ]}|t          |          nd S r   )rq   )r]  tzs     rz   	<setcomp>z1_parse_time_unit_and_time_zone.<locals>.<setcomp>  s&    FFFbc"gggTFFFry   )r   rq   r  r   )r  r  
time_units
time_zoness       rz   _parse_time_unit_and_time_zoner  
  s      	  i%%i[[^^   
 i#x11Gc)nnFFIFFF  z!!ry   r  rR   r   rY   r  Set[TimeUnit]r  Set[str | None]c                j    t          | |j                  o| j        |v o| j        |v pd|v o| j        d uS )N*)r   Datetimer  r  )r  r   r  r  s       rz   %dtype_matches_time_unit_and_time_zoner    sR     	5&/** 	
_
*	
 Oz) Cz!AeoT&Ary   c                   | j         S r   r   )r  s    rz   get_column_namesr  ,  s
    =ry   namesContainer[str]c                *    fd| j         D             S )Nc                    g | ]}|v|	S rx   rx   )r]  col_namer  s     rz   r  z(exclude_column_names.<locals>.<listcomp>1  s#    LLLhe6K6KH6K6K6Kry   r  )r  r  s    `rz   exclude_column_namesr  0  s    LLLLU]LLLLry   EvalNames[Any]c                    d fd}|S )N_framer   r   r   c                   S r   rx   )r  r  s    rz   rE  z$passthrough_column_names.<locals>.fn5  s    ry   )r  r   r   r   rx   )r  rE  s   ` rz   passthrough_column_namesr  4  s(          Iry   attrc                D    t                      }t          | ||          |uS r   )objectr
   )r  r  sentinels      rz   _hasattr_staticr  ;  s"    xxH#tX..h>>ry   [CompliantDataFrame[CompliantSeriesT, CompliantExprT, NativeFrameT_co, ToNarwhalsT_co] | Any]TypeIs[CompliantDataFrame[CompliantSeriesT, CompliantExprT, NativeFrameT_co, ToNarwhalsT_co]]c                "    t          | d          S )N__narwhals_dataframe__r  r  s    rz   is_compliant_dataframer  @  s     3 8999ry   ICompliantLazyFrame[CompliantExprT, NativeFrameT_co, ToNarwhalsT_co] | AnyKTypeIs[CompliantLazyFrame[CompliantExprT, NativeFrameT_co, ToNarwhalsT_co]]c                "    t          | d          S )N__narwhals_lazyframe__r  r  s    rz   is_compliant_lazyframer  K  s     3 8999ry   'CompliantSeries[NativeSeriesT_co] | Any)TypeIs[CompliantSeries[NativeSeriesT_co]]c                "    t          | d          S )N__narwhals_series__r  r  s    rz   r  r  Q  s     3 5666ry   c                R    t          |           o| j                                        S r   )r  r  
is_integerr  s    rz   r
  r
  W  s%     s##>	(<(<(>(>>ry   ECompliantExpr[CompliantFrameT, CompliantSeriesOrNativeExprT_co] | AnyGTypeIs[CompliantExpr[CompliantFrameT, CompliantSeriesOrNativeExprT_co]]c                "    t          | d          S )N__narwhals_expr__hasattrr  s    rz   is_compliant_exprr  ]  s     3+,,,ry   "TypeIs[EagerAllowedImplementation]c                x    | t           j        t           j        t           j        t           j        t           j        hv S r   )r   r   r   r   r   r   r  s    rz   is_eager_allowedr  c  s2      ry   TypeIs[SupportsNativeNamespace]c                "    t          | d          S )Nr  r  r  s    rz   has_native_namespacer  m  s    3.///ry   TypeIs[DataFrameLike]c                "    t          | d          S )N__dataframe__r  r  s    rz   _supports_dataframe_interchanger  q  s    3(((ry   TypeIs[ArrowStreamExportable]c                "    t          | d          S )N__arrow_c_stream__r  r  s    rz   supports_arrow_c_streamr  u  s    3 4555ry   left_onright_ondict[str, str]c                ^      fd|D             }t          t          ||                    S )aO  Remap join keys to avoid collisions.

    If left keys collide with the right keys, append the suffix.
    If there's no collision, let the right keys be.

    Arguments:
        left_on: Left keys.
        right_on: Right keys.
        suffix: Suffix to append to right keys.

    Returns:
        A map of old to new right keys.
    c              3  0   K   | ]}|v r|  n|V  d S r   rx   )r]  keyr  rA  s     rz   r_  z(_remap_full_join_keys.<locals>.<genexpr>  sL        8;C7NN3     ry   )dictzip)r  r  rA  right_keys_suffixeds   ` ` rz   _remap_full_join_keysr  y  sM         ?G   H122333ry   datarL   contextpa.Tablec                   t          d          rLddl}ddlm} |j        } |t          |          |          }|j                            | |          j        S dt          |           d}t          |          )	zGuards `ArrowDataFrame.from_arrow` w/ safer imports.

    Arguments:
        data: Object which implements `__arrow_c_stream__`.
        context: Initialized compliant object.

    Returns:
        A PyArrow Table.
    r   r   N)ArrowNamespace)r6  rU  )r  zB'pyarrow>=14.0.0' is required for `from_arrow` for object of type r`  )r	   r   narwhals._arrow.namespacer  r   r$  
_dataframe
from_arrowr   rQ  ModuleNotFoundError)r  r  r   r  rU  r  r  s          rz   _into_arrow_tabler    s      
'<<<<<<"^M",=,=wOOO}''b'99@@qSfgkSlSlqqq!#&&&ry   rE  c                   | S )a  Visual-only marker for unstable functionality.

    Arguments:
        fn: Function to decorate.

    Returns:
        Decorated function (unchanged).

    Examples:
        >>> from narwhals._utils import unstable
        >>> @unstable
        ... def a_work_in_progress_feature(*args):
        ...     return args
        >>>
        >>> a_work_in_progress_feature.__name__
        'a_work_in_progress_feature'
        >>> a_work_in_progress_feature(1, 2, 3)
        (1, 2, 3)
    rx   )rE  s    rz   unstabler    s	    ( Iry   formatc                <     t           fddD                        S )a  Determines if a datetime format string is 'naive', i.e., does not include timezone information.

    A format is considered naive if it does not contain any of the following

    - '%s': Unix timestamp
    - '%z': UTC offset
    - 'Z' : UTC timezone designator

    Arguments:
        format: The datetime format string to check.

    Returns:
        bool: True if the format is naive (does not include timezone info), False otherwise.
    c              3      K   | ]}|v V  	d S r   rx   )r]  xr  s     rz   r_  z#_is_naive_format.<locals>.<genexpr>  s'      ::11;::::::ry   )z%sz%zZ)any)r  s   `rz   _is_naive_formatr    s,     ::::(9:::::::ry   c                  X    e Zd ZdZdddZdd	ZddZ	 dddZddZe	d d            Z
dS )!not_implementeda  Mark some functionality as unsupported.

    Arguments:
        alias: optional name used instead of the data model hook [`__set_name__`].

    Returns:
        An exception-raising [descriptor].

    Notes:
        - Attribute/method name *doesn't* need to be declared twice
        - Allows different behavior when looked up on the class vs instance
        - Allows us to use `isinstance(...)` instead of monkeypatching an attribute to the function

    Examples:
        >>> from narwhals._utils import not_implemented
        >>> class Thing:
        ...     def totally_ready(self) -> str:
        ...         return "I'm ready!"
        ...
        ...     not_ready_yet = not_implemented()
        >>>
        >>> thing = Thing()
        >>> thing.totally_ready()
        "I'm ready!"
        >>> thing.not_ready_yet()
        Traceback (most recent call last):
            ...
        NotImplementedError: 'not_ready_yet' is not implemented for: 'Thing'.
        ...
        >>> isinstance(Thing.not_ready_yet, not_implemented)
        True

    [`__set_name__`]: https://docs.python.org/3/reference/datamodel.html#object.__set_name__
    [descriptor]: https://docs.python.org/3/howto/descriptor.html
    Nalias
str | Noner   r7  c                   || _         d S r   )_alias)r   r  s     rz   __init__znot_implemented.__init__  s     #(ry   rq   c                P    dt          |           j         d| j         d| j         S )N<z>: r`  )rd  rt   _name_owner_namer   s    rz   __repr__znot_implemented.__repr__  s.    J4::&JJ4+;JJdjJJJry   r~   rf  namec                :    |j         | _        | j        p|| _        d S r   )rt   r  r  r  )r   r~   r  s      rz   __set_name__znot_implemented.__set_name__  s     %+-


ry   r}   _T | Literal['raise'] | Nonetype[_T] | Noner   c               `    || S t          |d| j                  }t          | j        |          )Nr   )r  r  _not_implemented_errorr  )r   r}   r~   whos       rz   r   znot_implemented.__get__  s:      K h 143CDD$TZ555ry   rE  rI  c                ,    |                      d          S )Nraise)r   )r   rE  rI  s      rz   __call__znot_implemented.__call__  s     ||G$$$ry   r7  r<   r>   c               F     |             } t          |          |          S )a  Alt constructor, wraps with `@deprecated`.

        Arguments:
            message: **Static-only** deprecation message, emitted in an IDE.

        Returns:
            An exception-raising [descriptor].

        [descriptor]: https://docs.python.org/3/howto/descriptor.html
        r   )r   r7  r  s      rz   r   znot_implemented.deprecated  s'     cee"z'""3'''ry   r   )r  r  r   r7  r&  )r~   rf  r  rq   r   r7  )r}   r  r~   r  r   r   )rE  r   rI  r   r   r   )r7  r<   r   r>   )rt   ru   rv   r   r  r  r  r   r	  r'  r   rx   ry   rz   r  r    s        " "H( ( ( ( (
K K K K. . . . PT6 6 6 6 6% % % %
 ( ( ( [( ( (ry   r  whatr  NotImplementedErrorc               0    | d|d}t          |          S )Nz is not implemented for: z.

If you would like to see this functionality in `narwhals`, please open an issue at: https://github.com/narwhals-dev/narwhals/issues)r  )r  r  r  s      rz   r  r  %  s:     	S 	SC 	S 	S 	S 
 s###ry   c                  j    e Zd ZU dZded<   ded<   eddd            Zedd            ZddZ	ddZ
dS )requiresa#  Method decorator for raising under certain constraints.

    Attributes:
        _min_version: Minimum backend version.
        _hint: Optional suggested alternative.

    Examples:
        >>> from narwhals._utils import requires, Implementation
        >>> class SomeBackend:
        ...     _implementation = Implementation.PYARROW
        ...     _backend_version = 20, 0, 0
        ...
        ...     @requires.backend_version((9000, 0, 0))
        ...     def really_complex_feature(self) -> str:
        ...         return "hello"
        >>> backend = SomeBackend()
        >>> backend.really_complex_feature()
        Traceback (most recent call last):
            ...
        NotImplementedError: `really_complex_feature` is only available in 'pyarrow>=9000.0.0', found version '20.0.0'.
    r   _min_versionrq   _hintrX  hintminimumr   r>   c               L    |                      |           }||_        ||_        |S )zMethod decorator for raising below a minimum `_backend_version`.

        Arguments:
            minimum: Minimum backend version.
            hint: Optional suggested alternative.

        Returns:
            An exception-raising decorator.
        )__new__r  r  )r   r  r  r  s       rz   r6  zrequires.backend_versionH  s)     kk#"	
ry   r6  c               @    d                     d | D                       S )Nr`  c              3     K   | ]}| V  d S r   rx   )r]  ds     rz   r_  z,requires._unparse_version.<locals>.<genexpr>Z  s$      8811888888ry   )r  )r6  s    rz   _unparse_versionzrequires._unparse_versionX  s#    xx88888888ry   r}   r   r7  c          	        |j         | j        k    rd S | j        }|j        }|                     | j                  }|                     |j                   }d| d| d| d|d	}| j        r| d| j         }t          |          )N`z` is only available in 'z>=z', found version r`  
)r   r  _wrapped_namer   r  r  r  )r   r}   methodr   r  foundr  s          rz   _ensure_versionzrequires._ensure_version\  s    $(999F#*''(9::%%h&?@@a&aa'aaWaaW\aaa: 	)((DJ((C!#&&&ry   rE  _Method[_ContextT, P, R]c               Z     j          _        t                    d
 fd	            }|S )Nr}   r   rE  rH  rI  rJ  r   rl   c                F                         |             | g|R i |S r   )r   )r}   rE  rI  rE  r   s      rz   rM  z"requires.__call__.<locals>.wrapperk  s7      ***2h.......ry   )r}   r   rE  rH  rI  rJ  r   rl   )rt   r  r   )r   rE  rM  s   `` rz   r	  zrequires.__call__h  sH    [	r	/ 	/ 	/ 	/ 	/ 	/ 
	/
 ry   N)rX  )r  rq   r  r   r   r>   )r6  r   r   rq   )r}   r   r   r7  )rE  r!  r   r!  )rt   ru   rv   r   rw   r'  r6  staticmethodr  r   r	  rx   ry   rz   r  r  .  s          , "!!!JJJ    [ 9 9 9 \9
' 
' 
' 
'	 	 	 	 	 	ry   r  	str_slicerc   "tuple[int | None, int | None, Any]c                    | j         |                    | j                   nd }| j        |                    | j                  dz   nd }| j        }|||fS )Nr1  )r  r  r  r  )r%  r   r  r  r  s        rz   convert_str_slice_to_int_slicer(  t  s\     /8o.IGMM)/***tE090J7==((1,,PTD>D4ry   	tp_parentCallable[P, R1]<Callable[[_Constructor[_T, P, R2]], _Constructor[_T, P, R2]]c                    d fd}|S )zSteal the class-level docstring from parent and attach to child `__init__`.

    Returns:
        Decorated constructor.

    Notes:
        - Passes static typing (mostly)
        - Passes at runtime
    
init_child_Constructor[_T, P, R2]r   c                   | j         dk    r8t          t                    t                    rt                    | _        | S dt
          j          d| j        d}t          |          )Nr  z`@zL` is only allowed to decorate an `__init__` with a class-level doc.
Method: z	
Parent: )rt   r}  rd  r   r   inherit_docrv   rR  )r-  r  r)  s     rz   rN  zinherit_doc.<locals>.decorate  s    *,,DOOT1R1R,!'	!2!2J)[) ) )%2) )$) ) 
 C.. ry   )r-  r.  r   r.  rx   )r)  rN  s   ` rz   r0  r0  }  s(    
! 
! 
! 
! 
! 
! Ory   object | type[Any]c                   t          | t                    r| nt          |           }|j        dk    r|j        nd}| d|j                             d          S )NbuiltinsrX  r`  )r   rd  ru   rt   lstrip)r  r  modules      rz   rQ  rQ    s[    3%%	4499B mz99R]]rF$$r{$$++C000ry   rU  valid_types	type[Any]rV  c                 t          | |          sd                    d |D                       }d|dt          |           }|rnd}t          |           }t	          |          dk    rt          |            d}| | d}d	t	          |          z  d
t	          |          z  z   }| d| | d| }t          |          dS )a  Validate that an object is an instance of one or more specified types.

    Parameters:
        obj: The object to validate.
        *valid_types: One or more valid types that `obj` is expected to match.
        param_name: The name of the parameter being validated.
            Used to improve error message clarity.

    Raises:
        TypeError: If `obj` is not an instance of any of the provided `valid_types`.

    Examples:
        >>> from narwhals._utils import ensure_type
        >>> ensure_type(42, int, float)
        >>> ensure_type("hello", str)

        >>> ensure_type("hello", int, param_name="test")
        Traceback (most recent call last):
            ...
        TypeError: Expected 'int', got: 'str'
            test='hello'
                 ^^^^^^^
        >>> import polars as pl
        >>> import pandas as pd
        >>> df = pl.DataFrame([[1], [2], [3], [4], [5]], schema=[*"abcde"])
        >>> ensure_type(df, pd.DataFrame, param_name="df")
        Traceback (most recent call last):
            ...
        TypeError: Expected 'pandas.core.frame.DataFrame', got: 'polars.dataframe.frame.DataFrame'
            df=polars.dataframe.frame.DataFrame(...)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    z | c              3  4   K   | ]}t          |          V  d S r   )rQ  )r]  r  s     rz   r_  zensure_type.<locals>.<genexpr>  s+      LL"1"55LLLLLLry   z	Expected z, got: z    (   z(...)=rb  ^r  N)r   r  rQ  reprr?  rR  )	r  rV  r6  tp_namesr  left_padvalassign	underlines	            rz   rW  rW    s    B c;'' ::LLLLLLLI(II-@-E-EII 	7Hs))C3xx"}},S11888 /*///Fs6{{*sSXX~>I66F6C66966Cnn ry   c                  *    e Zd ZdZddZddZdd
ZdS )_DeferredIterablezLStore a callable producing an iterable to defer collection until we need it.	into_iterCallable[[], Iterable[_T]]r   r7  c                   || _         d S r   
_into_iter)r   rE  s     rz   r  z_DeferredIterable.__init__  s    6?ry   Iterator[_T]c              #  >   K   |                                  E d {V  d S r   rH  r   s    rz   __iter__z_DeferredIterable.__iter__  s.      ??$$$$$$$$$$$ry   tuple[_T, ...]c                v    |                                  }t          |t                    r|nt          |          S r   )rI  r   rM  )r   its     rz   to_tuplez_DeferredIterable.to_tuple  s0    __E**9rrb		9ry   N)rE  rF  r   r7  )r   rJ  )r   rM  )rt   ru   rv   r   r  rL  rP  rx   ry   rz   rD  rD    sZ        VV@ @ @ @% % % %: : : : : :ry   rD  )r5  r   r6  r   r   r7  )r;  rq   r<  rq   r   rq   )r;  rq   rA  rq   r   rq   )rE  r   r   rF  )rK  r   r   r   )rK  rO  r   r  )rU  rV  r   r   )rc  rd  re  rf  r   rg  )rc  rk  re  rf  r   rl  )rc  rd  re  rn  r   ro  )rc  rk  re  rn  r   rq  )rc  rd  re  rs  r   rt  )rc  rk  re  rs  r   rv  )rc  r   re  rx  r   ry  )rc  r   re  r   r   r  )r~  r  r   r7  )r  re   r  r  r   re   )r  r  r   r   r   )r  re   r  r  r  r  r   re   )r  re   r   re   )r  r   r   r   r   r  )r  r  r   r   r   r  )r  re   rE  r  r  r  r   re   )r  rZ  r  r^   r   r  )r   r  r   r  )r  rZ  r   r   r   rq   )r  r   r  r  r  r  r   r  )r  r  r   r   )r  r   r   r  )r  r   r   r  )r  r  r   r  )r  r   r   r  )r  r   r   r  )r  r   r   r  )r  r   r   r  )r  r   r  rf  r   r  )r  r   r  rf  r   r   )r   rZ  )r7  rq   r   rq   r   r7  )
r  r<  r  r<  r=  r  r>  r  r   r  )rA  rq   rB  r  r   rC  )rP  rZ  rQ  rR  r   rS  )rY  rq   rZ  rq   r   rq   )r  r   r  r   r   rv  )r   r   r   r7  )r  r  r  r  r   r  )
r  rR   r   rY   r  r  r  r  r   r  )r  r   r   r   )r  r   r  r  r   r   )r  r   r   r  )r  r   r  rq   r   r  )r  r  r   r  )r  r  r   r  )r  r  r   r  )r  r  r   r  )r  r   r   r  )r  r   r   r  )r  r   r   r  )r  r   r   r  )r  r   r  r   rA  rq   r   r  )r  rL   r  r   r   r  )rE  rj   r   rj   )r  rq   r   r  )r  rq   r  rq   r   r  )r%  rc   r   r   r   r&  )r)  r*  r   r+  )r  r1  r   rq   )r  r   r6  r7  rV  rq   r   r7  )
__future__r   re  r[  datetimer   enumr   r   	functoolsr   importlib.utilr	   r)  r
   r   secretsr   typingr   r   r   r   r   r   r   r   r   r   r   r   r   r   warningsr   narwhals._enumr   narwhals._typing_compatr   narwhals.dependenciesr   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   narwhals.exceptionsr6   r7   r8   typesr9   r:   Setr   r   r   r   r   r   typing_extensionsr;   r<   r=   r>   r?   r@   narwhals._compliantrA   rB   rC   rD   rE   rF   rG   narwhals._compliant.typingrH   r   rI   rJ   narwhals._translaterK   rL   rM   r   rO   rP   r|  rR   r   rT   narwhals.typingrU   rV   rW   rX   rY   rZ   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   re   rg   rh   ri   rj   rk   rl   rm   rn   rp   r|   r   r   r   r   r   r   r   r   r   r   r   rw   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r4  r:  r@  rD  rJ  rN  rI  r$  rj  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r%  r6  r  r@  rO  rX  ru  r  r  r  r  r  r  r  r  r  r  r  r
  r  r  r  r  r  r  r  r  r  r  r  r  r(  r0  rQ  rW  rD  rx   ry   rz   <module>rd     s[   " " " " " " " 				 				                     $ $ $ $ $ $ * * * * * * * *                                             % % % % % % . . . . . .                                                 2 [ Z Z Z Z Z Z Z Z Z b0      ))))))                                 544444IIIIIIIIYYYYYYYYYY77777777%%%%%%&&&&&&                                   & WininfSk&Q R  N '%..C
'%..C
'%..C
'%3
4
4
4C	#AA	B	B    8   R R R R Rx R R RN N N N N N N N2 2 2 2 2 2 2 21 1 1 1 1 1 1 1    /       ,ox   0 0 0 0 0 0 0 0
 WT]]W\T222
4888GK~666	= = = = =< < < < <    HZ(       x.   4 4 4 4 4d 4 4 4n+ + + + +Z + + +F :*EF"F:4Z7             Q Q Q Q   S S S S(L L L L" 
   

 
      
 
 
" " " 
"
 
. . . 
.
 
( ( ( 
(
 
: : : 
:
 
   

      \ \ \ \~! ! ! !L ,0X EI	X X X X X Xv/ / / /d8 8 8 8	 	 	 	2 2 2 2j   2B B B BJL L L L"& "& "& "&J   L L L L9 9 9 9         " " " "D D D D   J J J J
   ' ' ' 'TU U U U   6 & & & & & &R$ $ $ $0   <   	" 	" 	" 	"" " " "*
 
 
 
   M M M M   ? ? ? ?
: : : :: : : :7 7 7 7? ? ? ?- - - -   0 0 0 0) ) ) )6 6 6 64 4 4 4,' ' ' '2   .; ; ; ;$Q( Q( Q( Q( Q( Q( Q( Q(h$ $ $ $C C C C C C C CL      81 1 1 1 IK , , , , , ,^: : : : : : : : : :ry   