L iR UddlmZddlZddlZddlZddlmZmZmZm Z m Z m Z ddl m Z ddlmZmZddlmZmZmZmZddlmZddlmZmZdd lmZdd lmZdd lm Z dd l!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,dd l-m.Z.ddl/m0Z0ddl1m2Z2m3Z3ddl4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEddlFmGZGmHZHmIZIe"rQddlmJZJddlKmLZLddlMZNddlOZPddlQZRddlSmTZTmUZUmVZVmWZWmXZXmYZYddlZm[Z[m\Z\m]Z]ddl^m_Z_ddl`maZambZbmcZcmdZdddlemfZfddlgmhZhmiZimjZjmkZkmlZlmmZmmnZnmoZompZpmqZqmrZrmsZsddltmuZumvZvmwZwddlxmyZymzZzm{Z{m|Z|m}Z}m~Z~mZmZmZmZmZmZmZmZmZmZmZddlmZmZddlmZddlmZddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZeZd ed!<e)d"e*ee#ee#ee#f#Ze)d$Ze)d%Ze)d&Ze)d'd(#ZeVd)Ze)d*Ze)d+Ze)d,ZGd-d.e(ZGd/d0e(ZGd1d2e(Ze)d3Ze)d4d56Ze)d7d56Zd8Zd ed9<e)d:e#Zd;Zd ed<<d=Zd ed><Gd?d@e(eZGdAdBe(eZGdCdDe(ZGdEdFe(ZGdGdHe(ZGdIdJeee(ZGdKdLeee(ZGdMdNee(ZGdOdPeZGdQdRe.ZejdSejdTejdUejdVejdWejdWejdXejdYejdZejd[ejd\i Zd]ed^<ejd_ejd`ejdaejdbiZdcedd< edefddgZeddhZddiZddjZddkZddlZddmZe, ddnZe, ddoZe, ddpZe, ddqZe, ddrZe, ddsZe, ddtZdduZddvZ ddwZddxZ dddy ddzZdd{Ze"r eed5|Zn#ddlZejd}k\r eed5|Zndd~ZddZ ddZ ddZddZddZ d ddZ d ddZ ddZddZddZ ddZ ddZddZddZddZ ddZddZ ddZddZ ddZddd ddZ ddZddZ ddZddZ ddZ ddZddZddZddZeZded<ddZ ddZ ddZ ddZ ddZddZddZddZddZddZddZ d dZ d dZ d dZ d dZ GddZd dZGddZ ddZ ddZddZddddZGdde&eZedfddZddZGddeeee(eZGd„de(eZGdĄdūZddƄZddDŽZ ddȄZGdɄdeZej>Zy() annotationsN) Collection ContainerIterableIteratorMappingSequence)timezone)Enumauto)cache lru_cachepartialwraps) find_spec)getattr_staticgetdoc)chain) attrgetter) token_hex) TYPE_CHECKINGAnyCallableFinalGenericLiteralProtocolTypeVarUnioncastoverload) NoAutoEnum)issue_deprecation_warning) assert_never deprecated)get_cudfget_dask_dataframe get_duckdbget_ibis get_modin get_pandas get_polars get_pyarrowget_pyspark_connectget_pyspark_sql get_sqlframeis_narwhals_seriesis_narwhals_series_intis_numpy_array_1dis_numpy_array_1d_intis_pandas_like_dataframeis_pandas_like_series)ColumnNotFoundErrorDuplicateErrorInvalidOperationError)Set) ModuleType) Concatenate LiteralString ParamSpecSelf TypeAliasTypeIs)CompliantExprTCompliantSeriesTNativeSeriesT_co)NamespaceAccessor)Accessor EvalNamesNativeDataFrameTNativeLazyFrameT Namespace) NativeArrow NativeCuDF NativeDask NativeDuckDB NativeIbis NativeModin NativePandasNativePandasLike NativePolars NativePySparkNativePySparkConnectNativeSQLFrame)ArrowStreamExportableIntoArrowTableToNarwhalsT_co)Backend IntoBackend _ArrowImpl _CuDFImpl _DaskImpl _DuckDBImpl_EagerAllowedImpl _IbisImpl_LazyAllowedImpl_LazyFrameCollectImpl _ModinImpl _PandasImpl_PandasLikeImpl _PolarsImpl_PySparkConnectImpl _PySparkImpl _SQLFrameImpl DataFrame LazyFrameDTypeSeries)CompliantDataFrameCompliantLazyFrameCompliantSeriesDTypes FileSource IntoSeriesTMultiIndexSelectorSingleIndexSelectorSizedMultiIndexSelectorSizeUnitSupportsNativeNamespaceTimeUnit_1DArray _SliceIndex _SliceName _SliceNoner@UnknownBackendNameFrameOrSeriesT)bound_T1_T2_T3_FnzCallable[..., Any]PRR1R2ceZdZUded<y)_SupportsVersionstr __version__N__name__ __module__ __qualname____annotations__U/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/narwhals/_utils.pyrrsrrceZdZdddZy) _SupportsGetNcyNrselfinstanceowners r__get__z_SupportsGet.__get__srr)rrr Any | Nonereturnr)rrrrrrrrrsQrrceZdZeddZy)_StoresColumnscyrrrs rcolumnsz_StoresColumns.columnss,/rN)r Sequence[str])rrrpropertyrrrrrrs / /rr_T NativeT_coT) covariant CompliantT_coz._FullContext | NamespaceAccessor[_FullContext] _IntoContext _IntoContextTz*Callable[Concatenate[_IntoContextT, P], R]_Methodz Callable[Concatenate[_T, P], R2] _Constructorc"eZdZdZeddZy) _StoresNativezProvides access to a native object. Native objects have types like: >>> from pandas import Series >>> from pyarrow import Table cy)zReturn the native object.Nrrs rnativez_StoresNative.native rN)rr)rrr__doc__rrrrrrr  rrc"eZdZdZeddZy)_StoresCompliantzProvides access to a compliant object. Compliant objects have types like: >>> from narwhals._pandas_like.series import PandasLikeSeries >>> from narwhals._arrow.dataframe import ArrowDataFrame cy)zReturn the compliant object.Nrrs r compliantz_StoresCompliant.compliantrrN)rr)rrrrrrrrrrrrrrceZdZeddZy)_StoresBackendVersioncy)z#Version tuple for a native package.Nrrs r_backend_versionz&_StoresBackendVersion._backend_versionrrNrtuple[int, ...])rrrrrrrrrrs   rrceZdZUded<y)_StoresVersionVersion_versionNrrrrrrs ,rrceZdZUded<y)_StoresImplementationImplementation_implementationNrrrrrrs ##IrrceZdZdZy)_LimitedContextzEProvides 2 attributes. - `_implementation` - `_version` NrrrrrrrrrrrceZdZdZy) _FullContextzMProvides 2 attributes. - `_implementation` - `_backend_version` NrrrrrrrrrceZdZdZddZy)ValidateBackendVersionz=Ensure the target `Implementation` is on a supported version.c8|jj}y)zRaise if installed version below `nw._utils.MIN_VERSIONS`. **Only use this when moving between backends.** Otherwise, the validation will have taken place already. N)rr)r_s r_validate_backend_versionz0ValidateBackendVersion._validate_backend_versions  1 1 3rN)rNone)rrrrrrrrrrs G4rrceZdZeZeZeZeddZeddZ ed dZ ed dZ ed dZ y) rcz|tjurddlm}|S|tjurddlm}|Sddlm}|S)NrrJ)rV1narwhals.stable.v1._namespacerKV2narwhals.stable.v2._namespacenarwhals._namespace)r NamespaceV1 NamespaceV2rKs r namespacezVersion.namespaces5 7::  N  7::  N 1rcz|tjurddlm}|S|tjurddlm}|Sddlm}|S)Nr)dtypes)rrnarwhals.stable.v1rrnarwhals.stable.v2narwhals)r dtypes_v1 dtypes_v2rs rrzVersion.dtypess4 7::  >  7::  > # rcz|tjurddlm}|S|tjurddlm}|Sddlm}|S)Nr)rm)rrrrmrrnarwhals.dataframe)r DataFrameV1 DataFrameV2rms r dataframezVersion.dataframe5 7::  C  7::  C 0rcz|tjurddlm}|S|tjurddlm}|Sddlm}|S)Nr)rn)rrrrnrrr)r LazyFrameV1 LazyFrameV2rns r lazyframezVersion.lazyframe#rrcz|tjurddlm}|S|tjurddlm}|Sddlm}|S)Nrrq)rrrrrrrnarwhals.series)rSeriesV1SeriesV2rrs rserieszVersion.series1s2 7::  =O 7::  =O* rN)rztype[Namespace[Any]])rrv)rztype[DataFrame[Any]])rztype[LazyFrame[Any]])rztype[Series[Any]]) rrrr rrMAINrrrrrrrrrrrsy B B 6D           rrc&eZdZdZdZ dZ dZ dZ dZ dZ dZ d Z d Z d Z d Z d Z d"dZe d#dZed$dZe d%dZd&dZd'dZd'dZd'dZd'dZd'dZd'dZd'dZd'dZd'dZd'dZd'dZ d'dZ!d'dZ"d(d Z#y!))rz?Implementation of native object (pandas, Polars, PyArrow, ...).pandasmodincudfpyarrowpysparkpolarsdaskduckdbibissqlframezpyspark[connect]unknownc,t|jSr)rvaluers r__str__zImplementation.__str__\s4::rcVttjttjt tj ttjttjttjttjttj t#tj$t'tj(t+tj,i }|j/|tj0S)zInstantiate Implementation object from a native namespace module. Arguments: native_namespace: Native namespace. )r+rPANDASr*MODINr&CUDFr-PYARROWr/PYSPARKr,POLARSr'DASKr(DUCKDBr)IBISr0SQLFRAMEr.PYSPARK_CONNECTgetUNKNOWN)clsnative_namespacemappings rfrom_native_namespacez$Implementation.from_native_namespace_s L.// K-- J++ M>11  ~55 L.//  ."5"5 L.// J++ NN33  !>#A#A  {{+^-C-CDDrcR ||S#t$rtjcYSwxYw)zInstantiate Implementation object from a native namespace module. Arguments: backend_name: Name of backend, expressed as string. ) ValueErrorrr)r backend_names r from_stringzImplementation.from_stringws- *|$ $ *!)) ) *s  &&ct|tr|j|St|tr|S|j |S)zInstantiate from native namespace module, string, or Implementation. Arguments: backend: Backend to instantiate Implementation from. ) isinstancerrrr)rbackends r from_backendzImplementation.from_backendsL'3' OOG $ '>2 **73  rc|tjur d}t||jtj ||j }t|S)zCReturn the native namespace module corresponding to Implementation.z:Cannot return native namespace from UNKNOWN Implementation)rrAssertionErrorr_IMPLEMENTATION_TO_MODULE_NAMErr_import_native_namespace)rmsg module_names rto_native_namespacez"Implementation.to_native_namespacesM >)) )NC % % 488tzzJ ' 44rc&|tjuS)a7Return whether implementation is pandas. 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 )rr rs r is_pandaszImplementation.is_pandas~,,,,rcd|tjtjtjhvS)aLReturn whether implementation is pandas, Modin, or cuDF. 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 )rr r r rs ris_pandas_likezImplementation.is_pandas_likes(--~/C/C^EXEXYYYrcd|tjtjtjhvS)aIReturn whether implementation is pyspark or sqlframe. 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 )rrrrrs r is_spark_likezImplementation.is_spark_likes1  " "  # #  * *   rc&|tjuS)a7Return whether implementation is Polars. 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 )rrrs r is_polarszImplementation.is_polarsr,rc&|tjuS)a4Return whether implementation is cuDF. 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 )rr rs ris_cudfzImplementation.is_cudf~****rc&|tjuS)a6Return whether implementation is Modin. 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 )rr rs ris_modinzImplementation.is_modins~++++rc&|tjuS)a:Return whether implementation is PySpark. 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 )rrrs r is_pysparkzImplementation.is_pyspark~----rc&|tjuS)aBReturn whether implementation is PySpark. 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 )rrrs ris_pyspark_connectz!Implementation.is_pyspark_connects~5555rc&|tjuS)a:Return whether implementation is PyArrow. 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 )rr rs r is_pyarrowzImplementation.is_pyarrow r:rc&|tjuS)a4Return whether implementation is Dask. 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 )rrrs ris_daskzImplementation.is_daskr5rc&|tjuS)a8Return whether implementation is DuckDB. 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 )rrrs r is_duckdbzImplementation.is_duckdb$r,rc&|tjuS)a4Return whether implementation is Ibis. 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 )rrrs ris_ibiszImplementation.is_ibis1r5rc&|tjuS)a<Return whether implementation is SQLFrame. 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 )rrrs r is_sqlframezImplementation.is_sqlframe>s~....rct|S)zReturns backend version.backend_versionrs rrzImplementation._backend_versionKs t$$rNrr)r type[Self]rr;rr)rrKrrrr)rrKr!z)IntoBackend[Backend] | UnknownBackendNamerr)rr;)rboolr)$rrrrr r r r rrrrrrrrr classmethodrrr"r)r+r.r0r2r4r7r9r<r>r@rBrDrFrrrrrr@s'I F E DG!G! F D F DH"(O)G!E E+5E EE. * *  "K   5 - Z " - + , . 6 . + - + /%rr)rN)r) ) )rO)r)irP)rNrN))rOrz(Mapping[Implementation, tuple[int, ...]] MIN_VERSIONSzdask.dataframez modin.pandasz pyspark.sqlzpyspark.sql.connectzMapping[Implementation, str]r%)maxsizecddlm}||S)Nr) import_module) importlibr^)r(r^s rr&r&gs'  %%rct|ts t||tjury|}tj ||j }t|}|jrddl }|j}n@|js|jrddl }|}n|jrddl}|}n|}t!|}|t"|x} krd|d| d|} t%| |S)N)rrrrzMinimum version of z supported by Narwhals is z , found: )r rr$rr%rrr&rFsqlframe._versionrr9r<rr@r parse_versionrZr) implementationimplr(rr into_versionrrversion min_versionr's rrIrIqs nn 5^$/// D044T4::FK/ <  ((  d557  ' L)Gd!33+4#D6)CK=PYZaYbco Nrcbtt|dk(rt|dr |dS|S)NrNr)listlen _is_iterable)argss rflattenrms. CIN|DG/DQ PP4 PPrc8t|ttfs|fS|Sr)r rituple)args rtupleifyrqs cD%= )v Jrczddlm}tx}"t||j|jfsDt x}Rt||j|j |j|jfrdt|d}t|t|txrt|tt|f S)Nrrqz(Expected Narwhals class or scalar, got: z`. Hint: Perhaps you - forgot a `nw.from_native` somewhere? - used `pl.col` instead of `nw.col`?) rrrr+r rmr,Exprrnqualified_type_name TypeErrorrrbytes)rprrpdplr's rrkrks&| (Zbii=V-W| ( sRYYr||L M77J37O6RS3 3 n c8 $ RZc5&=Q-R)RRrc"t|tSr)r r)vals r is_iteratorr{s c8 $$rct|tr|n |j}tjdd|}t d|j dDS)zSimple version parser; split into a tuple of ints for comparison. Arguments: version: Version string, or object with one, to parse. z (\D?dev.*$)c3\K|]$}ttjdd|&yw)z\Dr}N)intresub).0vs r z parse_version..s"KqRVVE2q)*Ks*,.)r rrrrrosplit)rf version_strs rrbrbsH(5'7;N;NK&&[9K KK4E4Ec4JK KKrcyrr obj_or_cls cls_or_tuples risinstance_or_issubclassrsrcyrrrs rrr rcyrrrs rrrs"rcyrrrs rrrs+.rcyrrrs rrrs%(rcyrrrs rrrs7:rcyrrrs rrrsrcddlm}t||r t||St||xst|txr t ||S)Nrro)narwhals.dtypesrpr type issubclass)rrrps rrrsF%*e$*l33 j, / :t$MJ )Mrcddlmmtfd|Dstfd|Dryd|Dcgc] }t |c}}t |cc}w)Nrrlc36K|]}t|ywrr )ritemrms rrz$validate_laziness..s 94:dI & 9c36K|]}t|ywrr)rrrns rrz$validate_laziness..s :DJtY ' :rzGThe items to concatenate should either all be eager, or all lazy, got: )rrmrnallrru)itemsrr'rmrns @@rvalidate_lazinessrsW7 95 99 :E :: SlqTrdhUYZ^U_TrSs tC C.UssAcddlm}ddlm}d d}t d|}t d|}t t |dd|rt t |dd|r||jjj||jjj|j|jj|jjj|jjjSt t |dd|rt t |dd|r||jjj||jjj|j|jj|jjj|jjjSt t |dd|rt t |dd|r||jjj||jjj|j|jj|jjj|jjjSt t |dd|rt t |dd|r||jjj||jjj|j|jj|jjj|jjjSt|t|k7r%d t|d t|}t||S) aAlign `lhs` to the Index of `rhs`, if they're both pandas-like. Arguments: lhs: Dataframe or Series. rhs: Dataframe or Series to align with. 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)PandasLikeSeriesrc6|js d}t|y)Nz'given index doesn't have a unique index) is_uniquer)indexr's r_validate_indexz*maybe_align_index.._validate_index!s;CS/ !r_compliant_frameN_compliant_seriesz6Expected `lhs` and `rhs` to have the same length, got z and )rrrr)narwhals._pandas_like.dataframernarwhals._pandas_like.seriesrr r getattrrrr_with_compliant _with_nativelocrrjr)lhsrhsrrrlhs_anyrhs_anyr's rmaybe_align_indexrsI<D=" 5#G5#G+T24G WW&8$?AT U0077==>0077==>&&  $ $ 1 1((//33G4L4L4S4S4Y4YZ   +T24G WW&94@BR S0077==>1188>>?&&  $ $ 1 1((//33--44::   ,d35E WW&8$?AT U1188>>?0077==>&&  % % 2 2))0044,,3399   ,d35E WW&94@BR S1188>>?1188>>?&&  % % 2 2))0044--44::    7|s7|#Fs7|nTYZ]^eZfYgho Jrctd|}|j}t|s t|r |jSy)aGet the index of a DataFrame or a Series, if it's pandas-like. Arguments: obj: Dataframe or 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 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) rN)r to_nativer5r6r)objobj_any native_objs rmaybe_get_indexr\s=45#G""$J +/DZ/P r)rcVddlm}td|}|j}|| d}t||s| d}t||.t |r|Dcgc] }||dc}n ||d}n|}t |r9|j |jj|j|St|r^ddl m } |r d }t|| |||jj }|j |jj|S|Scc}w) aSet 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. 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)rrz8Only one of `column_names` or `index` should be providedz3Either `column_names` or `index` should be providedT) pass_through) set_indexz/Cannot set index using column names on a Series)rc)narwhals.translaterr rrkr5rrrrr6narwhals._pandas_like.utilsrr) r column_namesrrdf_anyrr'idxkeysrs rmaybe_set_indexr}s7X- % F!!#JE$5Ho EMCo E";@ @3Ys . @5t4  +%%  # # 0 01E1Ed1K L  Z(9 CCS/ !  00@@ %%f&>&>&K&KJ&WXX M1 AsD&ctd|}|j}t|rX|j}t ||r|S|j |j j|jdSt|rX|j}t ||r|S|j |jj|jdS|S)aReset the index to the default integer index of a DataFrame or a Series, if it's pandas-like. Arguments: obj: Dataframe or Series. 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) rT)drop) r rr5__native_namespace___has_default_indexrrr reset_indexr6r)rrrrs rmaybe_reset_indexrs85#G""$J +"779 j*: ;N&&  $ $ 1 1*2H2Hd2H2S T  Z("779 j*: ;N&&  % % 2 2:3I3It3I3T U   Nr)strict)rOrSct|dkrt|Sddfd }dfd }t|}tt ||}t t t|tt|g|S)NrQFc3Kdyw)NTr) first_stoppedsr first_tailzzip_strict..first_tails $ sc3xKs d}t|tjD]}d}t|yw)Nz$zip_strict: first iterable is longerz%zip_strict: first iterable is shorter)rr from_iterable)r'rrrests rzip_tailzzip_strict..zip_tailsB$@C$S/),,T2AAC$S/)s7:)rr)rjzipiterrnextrimap) iterablesrr iterables_itfirstrrs @@r zip_strictr sp9~!I&!M   ?L$|,jl;ED,/0DU*T*HJ7 7rc.t||jSr)r  RangeIndex)rrs r_is_range_indexr*s c+66 77rc|j}t||xr:|jdk(xr)|jt |k(xr|j dk(S)NrrN)rrstartstoprjstep)native_frame_or_seriesrrs rrr.sW # ( (E/0  KK1   JJ#e* $  JJ!O rc |jjs|S|j|jj |j j |i|}td|S)a-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. 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)rcr.r _compliantrrconvert_dtypesr )rrlkwargsresults rmaybe_convert_dtypesr:sgB    , , .   ##$BCMMO$B$BD$SF$STF  & ))rcv|dvr|S|dvr|dz S|dvr|dz S|dvr|dz S|dvr|d z Sd |}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 >brv>kb kilobytesi>mb megabytesi>gb gigabytesi@>tb terabyteslz9`unit` must be one of {'b', 'kb', 'mb', 'gb', 'tb'}, got r)szunitr's r scale_bytesrcss ~  ""Dy ""G| ""G| ""G| Gx PC S/rcddlm}|jjj}|j}d}t ||r;t |j |jr|jjd}|S|j |jk(rd}|S|j |jk7rd}|S|j}|j}|jr8|jdkr%td|j j dk(}|S|j#r!t%|j&j(}|S|j+r0dd lm}||j0xr|j0j(}|S) aReturn 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. 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="lexical")) 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) False r)InterchangeSeriesF is_orderedT)rN zpl.Categoricalphysical) is_dictionary)narwhals._interchange.seriesrrrrr dtype Categoricalrdescribe_categoricalr rrcr2rr orderingr.rLcatorderedr>narwhals._arrow.utilsrr)rrrrrrrdrs ris_ordered_categoricalrxsaN?  % % . . 5 5F((IF)./J f((5!!66|D& M%  $" M! ++ + M!!#$$ >>  5 5 7' A*FLL9BBjPF M  "&**,,-F M __  ;"6;;/GFKK4G4GF Mrc<d}t|dt|||S)Nz}Use `generate_temporary_column_name` instead. `generate_unique_token` is deprecated and it will be removed in future versionsz1.13.0r)n_bytesrprefix)r#generate_temporary_column_name)r rr r's rgenerate_unique_tokenr s( ?cH5 )'7SY ZZrctd} |t|dz }||vr|S|dz }|dkDrd|d|}t|6)aGenerates 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. prefix: prefix with which the temporary column name should start with. 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 >>> temp_name = nw.generate_temporary_column_name( ... n_bytes=8, columns=columns, prefix="foo" ... ) >>> temp_name not in columns and temp_name.startswith("foo") True rrNdzMInternal Error: Narwhals was not able to generate a column name with n_bytes=z and not in )rr$)r rr countertokenr's rr r sm<G (9Wq[123  L1  S=*L 3 !% % rc|s-tt|jj|St|}t ||jx}r||S)N) available)risetr intersectioncheck_columns_exist)framesubsetrto_droperrors rparse_columns_to_droprsO C &33F;<<6lG#Gu}}EEuE NrcHt|txrt|t Sr)r r r)sequences ris_sequence_but_not_strrs h ) K*Xs2K.KKrcBt|txr|tdk(Sr)r slicers r is_slice_noner!s c5 ! 8cU4[&88rct|xr3t|dkDxrt|dtxst|dk(xs%t |xst |xs t |SNr)rrjr rr4r2is_compliant_series_intr s ris_sized_multi_index_selectorr% sl $C ( Pc(Q,::c!fc#:NCA  ( ! %  ( "# &  ( #3 'rcft|xs%t|xst|xs t|Sr)rr3r1is_compliant_seriesr s ris_sequence_liker(s: $ $ S ! $ c " $ s # rc t|txrrt|jtxsVt|jtxs:t|j txr|jduxr|jduSr)r rrrrrr s ris_slice_indexr*"sh c5 ! 399c" R chh $ R sxx % P#))t*; PD@Prc"t|tSr)r ranger s ris_ranger-*s c5 !!rcZtt|txrt|t Sr)rLr rr s ris_single_index_selectorr/.s#  3$BZT-B)B CCrcLt|xst|xs t|Sr)r/r%r*r s ris_index_selectorr12s+ !%  ( -  # rc^tt|txr|xrt|d|Sr#)rLr ri)rtps r is_list_ofr4<s)  3%H#H*SVR2H IIrc&td|DS)Nc3<K|]}t|tywr)r4rL)rpreds rrz3predicates_contains_list_of_bool..Ds=$z$%=sany) predicatess r predicates_contains_list_of_boolr;As =*= ==rcxtt|xr%tt|dx}xr t ||Sr)rLrrrr )rr3rs ris_sequence_ofr=Gs> $ "49d+ +U " ub ! rcL|||}|S||| }|S|| |Sd}t|)Nz,Cannot pass both `strict` and `pass_through`r)rrpass_through_defaultr's rvalidate_strict_and_pass_thoughr@Ps_ ~,.+     4!z  L4  =orr}F) warn_versionrequiredcdfd }|S)a8Decorator 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**. c6tdfd }|S)Nc|jdd}|jdd}||rd}t||}n2|| d}t|||rdjd}t|||d<|i|S)Nr!rz`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. rz0Can't pass both `native_namespace` and `backend`z `backend` must be specified in `z`.)popr#rr)rlkwdsr!rr'fnrBrAs rwrapperz=deprecate_native_namespace..decorate..wrapperpshhy$/G#xx(:DA +j .cLI*!-'2EH o%!)go(8 RH o%%DOt$t$ $r)rlP.argsrGP.kwargsrr)r)rHrIrBrAs` rdecoratez,deprecate_native_namespace..decorateos r %  %*r)rHCallable[P, R]rrMr)rArBrLs`` rdeprecate_native_namespacerNbs2 Orct|tdt|ttdd|dkr d}t||(|dkr d}t|||kDr d}t |||fS|}||fS)N window_size param_name min_samplesrNz+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_typerrrr9)rPrSr's r_validate_rolling_argumentsrUs S]; S$t*GQ;o ??CS/ !  $JC', ,  ##"  ##rc  tjj}|j j}td|D}|dz|krt|t|}dd|zd}|t|z }|dd |dzz|d |dz|dzzzd z }|dd |zd z }||z dz}||z dz||z dzz} |D]$} |dd |z| d | |zt| z zd z }&|d d|zd z }|Sdt|z } dddd | dzz|d | dz| dzzzddd S#t$r#t tj dd}Y:wxYw)NCOLUMNSPc32K|]}t|ywr)rj)rlines rrz generate_repr..s>3t9>rQu┌u─u┐ | z| -u└u┘'uu───────────────────────────────────────u┐ |u/| | Use `.to_native` to see native output | └) osget_terminal_sizerOSErrorrgetenv expandtabs splitlinesmaxrj) header native_reprterminal_width native_linesmax_native_widthlengthoutput header_extra start_extra end_extrarZdiffs r generate_reprrrs7--/77))+668L>>>!~-%s6{3uv~&e,F + Ac\Q./0 PQ@QT`cdTd@d9e8ffijjAcVn%S)) 00Q6 ..14AQ8QUV7VV   kD #-.tfSIHX.s#LAaS1#V,Lsz"Expected unique column names, got:)rjr collectionsrxrjoinr8)rrxrrzr duplicatesr's rcheck_column_names_are_uniquer~s 7|s3w<((''"'.}}@tq!!a%ad@ @ggL9I9I9KLL23%8S!!)As  BBc|hdnt|tr|hn t|}|dhn>t|ttfr t|hn|Dchc]}| t|ndc}}||fScc}w)N>smsnsus)r rrr ) time_unit time_zone time_unitstz time_zoness r_parse_time_unit_and_time_zoners    i %[ ^     i#x 1)n .fns r)rrrrr)rrHs` rpassthrough_column_namesrs Irr _SENTINELc0t||ttuSr)rr)rattrs r_hasattr_staticr s #tY /y @@rct|dS)N__narwhals_dataframe__rr s ris_compliant_dataframers 3 8 99rct|dS)N__narwhals_lazyframe__rr s ris_compliant_lazyframers 3 8 99rct|dS)N__narwhals_series__rr s rr'r's 3 5 66rcPt|xr|jjSr)r'r is_integerr s rr$r$%s! s # > (<(<(>>rc6t|dxr t|dS)Nr _accessorrr s r_is_namespace_accessorr+s 3 , Rk1RRrc|tjtjtjtjtj hvS)z.Return True if `impl` allows eager operations.)rr r r rr rds ris_eager_allowedr5sA   rcd|tjtjtjhvS)z4Return True if `LazyFrame.collect(impl)` is allowed.)rr rr rs rcan_lazyframe_collectr@s& N))>+@+@.BXBXY YYrc|tjtjtjtjtj tj tjhvS)z1Return True if `DataFrame.lazy(impl)` is allowed.)rrrrrrrrrs ris_lazy_allowedrEsS && rct|dS)Nrrr s rhas_native_namespacerRs 3 6 77rct|dS)N__arrow_c_stream__rr s rsupports_arrow_c_streamrVs 3 4 55rcHfd|D}tt||S)aORemap 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. c36K|]}|vr|n|ywrr)rkeyleft_onsuffixs rrz(_remap_full_join_keys..js*8;C7N3%x3r)dictr)rright_onrright_keys_suffixeds` ` r_remap_full_join_keysrZs( ?G H12 33rctdrV|jjjdj}|j j ||jSdt|d}t|)zGuards `ArrowDataFrame.from_arrow` w/ safer imports. Arguments: data: Object which implements `__arrow_c_stream__`. context: Initialized compliant object. r)contextzB'pyarrow>=14.0.0' is required for `from_arrow` for object of type r) rrrr"r _dataframe from_arrowrrtModuleNotFoundError)datarrr's r_into_arrow_tablerpsp    ' ' 4 4Y ? I I}}''b'9@@@ NObcgOhNkkl mC c ""rc|S)aVisual-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) r)rHs runstablers ( Irc.tfddD S)aDetermines 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. c3&K|]}|v ywrr)rxformats rrz#_is_naive_format..s:11;:s)z%sz%zZr8)rs`r_is_naive_formatrs:(9:: ::rcZeZdZdZd d dZd dZd dZ d d dZddZe ddZ y)not_implementedaMark 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 Nc||_yr)_alias)raliass r__init__znot_implemented.__init__s #( rcfdt|jd|jd|jS)N: r)rr _name_owner_namers r__repr__znot_implemented.__repr__s14:&&'s4+;+;*T>TU !7!7 7~&C""C$TZZ5rc$|jdS)Nraise)r)rrlrGs r__call__znot_implemented.__call__s||G$$rc2|}t||S)zAlt constructor, wraps with `@deprecated`. Arguments: message: **Static-only** deprecation message, emitted in an IDE. [descriptor]: https://docs.python.org/3/howto/descriptor.html )r%)rmessagers rr%znot_implemented.deprecatedse"z'"3''rr)rz str | NonerrrJ)rtype[_T]rrrr)rz_T | Literal['raise'] | Nonerztype[_T] | Nonerr)rlrrGrrr)rr=rr?) rrrrrrrrrrMr%rrrrrsU"H( K. PT4=L $%  ( (rrc(|d|d}t|)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)NotImplementedError)whatrr's rrrs, (+C73S S c ""rceZdZUdZded<ded<ded< edddZeddZdd Z dd Z dd Z dd Z y )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_versionr_hint _wrapped_namecD|j|}||_||_|S)zMethod decorator for raising below a minimum `_backend_version`. Arguments: minimum: Minimum backend version. hint: Optional suggested alternative. )__new__rr)rminimumhintrs rrIzrequires.backend_version's&kk#"  rc2djd|DS)Nrc3"K|]}| ywrr)rds rrz,requires._unparse_version..6s811#8s )r|rHs r_unparse_versionzrequires._unparse_version4sxx8888rcNd|jvr|d|j|_yyNr)r)rr s r_qualify_accessor_namezrequires._qualify_accessor_name8s/ d(( ($*81T-?-?,@!AD  )rct|r(|j|j|j}n|}|jt |j fSr)rrrrrrr)rrrs r_unwrap_contextzrequires._unwrap_context=sJ !( +  ' '(:(: ; **I I))3y/H/H+IIIrc $|j|\}}||jk\ry|j|j}|j|}d|jd|d|d|d }|jr|d|j}t |)N`z` is only available in 'z>=z', found version r )rrrrrr)rrrfr!rfoundr's r_ensure_versionzrequires._ensure_versionEs//9 d'' ' ''(9(9:%%g.$$$%%=gYb Qbchbkklm ::EDJJ<(C!#&&rcVj_tdfd }|S)Nc>j||g|i|Sr)r)rrlrGrHrs rrIz"requires.__call__..wrapperUs&   *h... .r)rrrlrJrGrKrr)rrr)rrHrIs`` rrzrequires.__call__Ps. [[ r /  / rN)r})rrrrrr?)rIrrr)r rFrr)rrrztuple[tuple[int, ...], str])rrrr)rH_Method[_IntoContextT, P, R]rr) rrrrrrMrI staticmethodrrrrrrrrrrsm,"! J   99B J ' .  % rrc|j|j|jnd}|j|j|jdznd}|j}|||fS)NrN)rrrr) str_slicerrrrs rconvert_str_slice_to_int_slicer^sZ/8oo.IGMM)// *tE090J7== (1 ,PTD >>D 4 rcdfd }|S)zSteal the class-level docstring from parent and attach to child `__init__`. Returns: Decorated constructor. Notes: - Passes static typing (mostly) - Passes at runtime c|jdk(r+tttrt|_|Sdt jd|j d}t|)Nrz`@zL` is only allowed to decorate an `__init__` with a class-level doc. Method: z Parent: )rrrrr inherit_docrru) init_childr' tp_parents rrLzinherit_doc..decoratetsp   * ,DOT1R!' !2J  %%&'!..12 m % nr)r _Constructor[_T, P, R2]rrr)r rLs` rr r gs  Orct|tr|n t|}|jdk7r |jnd}|d|jj dS)Nbuiltinsr}r)r rrrlstrip)rr3modules rrtrtsL3%49B mmz9R]]rFXQr{{m $ + +C 00rrQc:t||sdjd|D}d|dt|}|rYd}t|}t |dkDrt|d}||d}d t |zd t |zz}|d ||d |}t |y ) aValidate 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 | c32K|]}t|ywr)rt)rr3s rrzensure_type..sL"1"5Lr[z Expected z, got: z (z(...)=r]^rN)r r|rtrrjru) rrR valid_typestp_namesr'left_padrzassign underlines rrTrTsB c; '::L LL(W-@-E,HI Hs)C3x"},S12%8 z*Q/Fs6{*sSX~>IEF8C59+6Cn (rc(eZdZdZddZddZddZy) _DeferredIterablezLStore a callable producing an iterable to defer collection until we need it.c||_yr _into_iter)r into_iters rrz_DeferredIterable.__init__s 6?rc#@K|jEd{y7wrr rs r__iter__z_DeferredIterable.__iter__s??$$$s c\|j}t|tr|St|Sr)r!r ro)rits rto_tuplez_DeferredIterable.to_tuples& __ E*r9b 9rN)r"zCallable[[], Iterable[_T]]rr)rz Iterator[_T])rztuple[_T, ...])rrrrrr$r'rrrrrsV@%:rr@cJ|rdj|g|n|}t|Sr)r|r)rnestedrs rdeep_attrgetterr+s%(.388TOFO $DD d rc&t|g||S)z+Perform a nested attribute lookup on `obj`.)r+)rname_1r*s r deep_getattrr.s +?6 +F +C 00rc eZdZy) CompliantN)rrrrrrr0r0srr0c"eZdZdZeddZy)NarwhalsaMinimal *Narwhals-level* protocol. Provides access to a compliant object: obj: Narwhals[NativeT_co]] compliant: Compliant[NativeT_co] = obj._compliant Which itself exposes: implementation: Implementation = compliant.implementation native: NativeT_co = compliant.native This interface is used for revealing which `Implementation` member is associated with **either**: - One or more [nominal] native type(s) - One or more [structural] type(s) - where the true native type(s) are [assignable to] *at least* one of them These relationships are defined in the `@overload`s of `_Implementation.__get__(...)`. [nominal]: https://typing.python.org/en/latest/spec/glossary.html#term-nominal [structural]: https://typing.python.org/en/latest/spec/glossary.html#term-structural [assignable to]: https://typing.python.org/en/latest/spec/glossary.html#term-assignable cyrrrs rrzNarwhals._compliants36rN)rzCompliant[NativeT_co])rrrrrrrrrr2r2s066rr2cjeZdZdZddZeddZeddZeddZeddZe ddZeddZe dd Zedd Ze dd Zedd Zedd Ze d dZed!dZe d"dZed#dZd$dZy)%_ImplementationzDescriptor for matching an opaque `Implementation` on a generic class. Based on [pyright comment](https://github.com/microsoft/pyright/issues/3071#issuecomment-1043978070) c||_yr)rrs rrz_Implementation.__set_name__s ! rcyrrrs rrz_Implementation.__get__TWrcyrrrs rrz_Implementation.__get__r8rcyrrrs rrz_Implementation.__get__RUrcyrrrs rrz_Implementation.__get__PSrcyrrrs rrz_Implementation.__get__srcyrrrs rrz_Implementation.__get__r;rcyrrrs rrz_Implementation.__get__ s25rcyrrrs rrz_Implementation.__get__r8rcyrrrs rrz_Implementation.__get__srcyrrrs rrz_Implementation.__get__r=rcyrrrs rrz_Implementation.__get__r=rcyrrrs rrz_Implementation.__get__s.1rcyrrrs rrz_Implementation.__get__sKNrcyrrrs rrz_Implementation.__get__rrcyrrrs rrz_Implementation.__get__#sQTrc6||S|jjSr)rrrs rrz_Implementation.__get__%s'tPX-@-@-P-PPrN)r type[Any]rrrr)rzNarwhals[NativePolars]rrrrh)rzNarwhals[NativePandas]rrrrf)rzNarwhals[NativeModin]rrrre)rzNarwhals[NativeCuDF]rrrr^)rzNarwhals[NativePandasLike]rrrrg)rzNarwhals[NativeArrow]rrrr])rz3Narwhals[NativePolars | NativeArrow | NativePandas]rrrz&_PolarsImpl | _PandasImpl | _ArrowImpl)rzNarwhals[NativeDuckDB]rrrr`)rzNarwhals[NativeSQLFrame]rrrrk)rzNarwhals[NativeDask]rrrr_)rzNarwhals[NativeIbis]rrrrb)rz.Narwhals[NativePySpark | NativePySparkConnect]rrrz"_PySparkImpl | _PySparkConnectImpl)rrrztype[Narwhals[Any]]rr?)rzDataFrame[Any] | Series[Any]rrrra)rzLazyFrame[Any]rrrrc)rzNarwhals[Any] | Nonerrrr)rrrrrr!rrrrr5r5s| "WW WW UU SS 2;> UU 5K5TW5 /55WW 09< SS SS 1F1OR1 +11NN  4 =@   TTQrr5cpddl}t||jr|jj |S|Sr#)rr RecordBatchReaderTable from_batches)tblpas rto_pyarrow_tablerQ)s/#r++,xx$$S)) JrcTt|tr|Sddlm}t||S)Nr)Path)r rpathlibrS)sourcerSs rnormalize_pathrV1s#&#  tF| rcDt|tr|f|zSt|S)zEnsure the given bool or sequence of bools is the correct length. Stolen from https://github.com/pola-rs/polars/blob/b8bfb07a4a37a8d449d6d1841e345817431142df/py-polars/polars/_utils/various.py#L580-L594 )r rLro)rn_matchs r extend_boolrY9s#",E4!8E8g JeElJrceZdZdZddZy) _NoDefault NO_DEFAULTcy)Nz rrs rrz_NoDefault.__repr__IsrNrJ)rrr no_defaultrrrrr[r[DsJrr[)r(rrr;)rcrrr)rlrrz list[Any])rprrr)rpzAny | Iterable[Any]rrL)rzzIterable[_T] | AnyrzTypeIs[Iterator[_T]])rfz#str | ModuleType | _SupportsVersionrr)rrrrrzTypeIs[type[_T]])r object | typerrrzTypeIs[_T | type[_T]])rrrtuple[type[_T1], type[_T2]]rzTypeIs[type[_T1 | _T2]])rr_rr`rz#TypeIs[_T1 | _T2 | type[_T1 | _T2]])rrr&tuple[type[_T1], type[_T2], type[_T3]]rzTypeIs[type[_T1 | _T2 | _T3]])rr_rrarz/TypeIs[_T1 | _T2 | _T3 | type[_T1 | _T2 | _T3]])rrrztuple[type, ...]rz TypeIs[Any])rrrrrrL)r Iterable[Any]rr)rrrz-Series[Any] | DataFrame[Any] | LazyFrame[Any]rr)rz-DataFrame[Any] | LazyFrame[Any] | Series[Any]rrr)rrrzstr | list[str] | Nonerz6Series[IntoSeriesT] | list[Series[IntoSeriesT]] | Nonerr)rrrr)rrbrzIterable[tuple[Any, ...]])rrrrrzTypeIs[pd.RangeIndex])rzpd.Series[Any] | pd.DataFramerrrrL)rrrlrLrz bool | strrr)rrrr|rz int | float)rz Series[Any]rrL)nw)r rrContainer[str]r rrr)rrrz Iterable[str]rrLrz list[str])rSequence[_T] | AnyrTypeIs[Sequence[_T]])rrrzTypeIs[_SliceNone])rrrzCTypeIs[SizedMultiIndexSelector[Series[Any] | CompliantSeries[Any]]])rrerz-TypeIs[Sequence[_T] | Series[Any] | _1DArray])rrrzTypeIs[_SliceIndex])rrrz TypeIs[range])rrrzTypeIs[SingleIndexSelector])rrrzTTypeIs[SingleIndexSelector | MultiIndexSelector[Series[Any] | CompliantSeries[Any]]])rrr3rrzTypeIs[list[_T]])r:zCollection[Any]rzTypeIs[Collection[list[bool]]])rrr3rrrf)r bool | Nonerrgr?rLrrL)rArrBrLrz*Callable[[Callable[P, R]], Callable[P, R]])rPrrSz int | Nonerztuple[int, int])rgrrhrrr)rCollection[str]rrhrzColumnNotFoundError | None)rrhrr)rz$TimeUnit | Iterable[TimeUnit] | Nonerz7str | timezone | Iterable[str | timezone | None] | Nonerz%tuple[Set[TimeUnit], Set[str | None]]) rrprrvrz Set[TimeUnit]rzSet[str | None]rrL)rrrr)rrrrdrr)rrrzEvalNames[Any])rrrrrrL)rz\CompliantDataFrame[CompliantSeriesT, CompliantExprT, NativeDataFrameT, ToNarwhalsT_co] | Anyrz^TypeIs[CompliantDataFrame[CompliantSeriesT, CompliantExprT, NativeDataFrameT, ToNarwhalsT_co]])rzJCompliantLazyFrame[CompliantExprT, NativeLazyFrameT, ToNarwhalsT_co] | AnyrzLTypeIs[CompliantLazyFrame[CompliantExprT, NativeLazyFrameT, ToNarwhalsT_co]])rz'CompliantSeries[NativeSeriesT_co] | Anyrz)TypeIs[CompliantSeries[NativeSeriesT_co]])rrrz'TypeIs[NamespaceAccessor[_FullContext]])rdrrzTypeIs[_EagerAllowedImpl])rdrrzTypeIs[_LazyFrameCollectImpl])rdrrzTypeIs[_LazyAllowedImpl])rrrzTypeIs[SupportsNativeNamespace])rrrzTypeIs[ArrowStreamExportable])rrhrrhrrrzdict[str, str])rrYrrrpa.Table)rHrrr)rrrrL)rrrrrr)rrrrrz"tuple[int | None, int | None, Any])r zCallable[P, R1]rzr?r@rAnarwhals._compliantrBrCrD!narwhals._compliant.any_namespacerEnarwhals._compliant.typingrFrGrHrIrrKnarwhals._nativerLrMrNrOrPrQrRrSrTrUrVrWnarwhals._translaterXrYrZnarwhals._typingr[r\r]r^r_r`rarbrcrdrerfrgrhrirjrkrrmrnrrprrrnarwhals.typingrsrtrurvrwrxryrzr{r|r}r~rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr r r r rrrrrrrrZr%r&rIrmrqrkr{rbrrrrrrrr version_inforrrrrr r rrr!r%r(r*r-r/r1r4r;r=r@rNrUrrrr~rrrrrobjectrrrrr'r$rrrrrrrrrrrrrrr rtrTrr+r.r0r2r5rQrVrYr[r^rrrrs " XX66$*    &:<&[Z# WVC .    ZY&8%&&%( 'ininfSk&Q RN %.C %.C %.C %3 4C#A A B B8RxR00  T] \T 2 48 J iJ|< AA< i<  HZ(    x .   H -X- JHJ +^X(*? 42H 4IdIXM%ZM%b9)EF""F:6Z : 6 ).M""$9 @ < D 2&&<Q S*% L $,     -5     ""$?"" "  ..-H.(. .  (($J("( (  ::-S:4: :  #3  Y YKYYxF,0SEI S S(S B S  Sl,^T*J 7"S.  8<8 9 MP   &* &* $&*0:&*&*R*CN:>[ [)[36[[:>*& *&)*&36*&*&Z #0@DL9   H  2"D YJ >>#>     &&&)-&/&R$$#-$$0< .=""3"F"+"*     .; IX   M8 5A: :  :: S:Q: 7 07.7 ? 0?.? SZ 864 4(74AD44, # .;$S(S(l#SSl$1'A61 IK,^ : : 2 1 *4hz6J 7x #7:3Q3QlK K KK " " r