Ë
    ÚÍ:jç2  ã                  ó  — d Z ddlmZ ddlmZ ddlmZ ddlmZ ddl	m
Z
mZ ddlmZmZmZ ddlmZmZmZmZmZmZmZ e
r.dd	lmZ dd
l	mZmZ ddlZddlZddlm Z  ddl!m"Z" ddl#m$Z$m%Z%m&Z&m'Z' dgZ( G d„ dee)df   «      Z*y)zxSchema.

Adapted from Polars implementation at:
https://github.com/pola-rs/polars/blob/main/py-polars/polars/schema.py.
é    )Úannotations)ÚOrderedDict)ÚMapping)Úpartial)ÚTYPE_CHECKINGÚcast)ÚImplementationÚVersionÚqualified_type_name)Úget_cudfÚis_cudf_dtypeÚis_pandas_like_dtypeÚis_polars_data_typeÚis_polars_schemaÚis_pyarrow_data_typeÚis_pyarrow_schema)ÚIterable)ÚAnyÚClassVarN)ÚSelf)ÚDType)ÚDTypeBackendÚIntoArrowSchemaÚIntoPandasSchemaÚIntoPolarsSchemaÚSchemac                  ó  ‡ — e Zd ZU dZej
                  Zded<   	 d	 	 	 dˆ fd„Zdd„Z	dd„Z
dd„Zedd„«       Zedd	„«       Ze	 	 	 	 dd
„«       Zedd„«       Zdd„Z	 d	 	 	 dd„Zdd„Ze	 	 	 	 dd„«       Ze	 	 	 	 	 	 dd„«       Zˆ xZS )r   an  Ordered mapping of column names to their data type.

    Note:
        The pandas-like and dask backends allow non-string column names
        (e.g. integers or booleans). While discouraged, this is supported,
        so we cannot guarantee that the keys are strictly strings.

        See [concepts - column names](../concepts/column_names.md) for details.

    Arguments:
        schema: The schema definition given by column names and their associated
            *instantiated* Narwhals data type. Accepts a mapping or an iterable of tuples.

    Examples:
        Define a schema by passing *instantiated* data types.

        >>> import narwhals as nw
        >>> schema = nw.Schema({"foo": nw.Int8(), "bar": nw.String()})
        >>> schema
        Schema({'foo': Int8, 'bar': String})

        Access the data type associated with a specific column name.

        >>> schema["foo"]
        Int8

        Access various schema properties using the `names`, `dtypes`, and `len` methods.

        >>> schema.names()
        ['foo', 'bar']
        >>> schema.dtypes()
        [Int8, String]
        >>> schema.len()
        2
    zClassVar[Version]Ú_versionc                ó0   •— |xs i }t         ‰| �  |«       y ©N)ÚsuperÚ__init__)ÚselfÚschemaÚ	__class__s     €úd/home/mcse/projects/srt_converter/srt-converter-venv/lib/python3.12/site-packages/narwhals/schema.pyr"   zSchema.__init__T   s   ø€ ð ’˜2ˆÜ‰Ñ˜Õ ó    c                ó4   — t        | j                  «       «      S )ao  Get the column names of the schema.

        Note:
            The pandas-like and dask backends allow non-string column names
            (e.g. integers or booleans). While discouraged, this is supported,
            so the return type is not guaranteed to be `list[str]`.

            See [concepts - column names](../concepts/column_names.md) for details.
        )ÚlistÚkeys©r#   s    r&   ÚnameszSchema.namesZ   s   € ô �D—I‘I“KÓ Ð r'   c                ó4   — t        | j                  «       «      S )z!Get the data types of the schema.)r)   Úvaluesr+   s    r&   ÚdtypeszSchema.dtypesf   s   € ä�D—K‘K“MÓ"Ð"r'   c                ó   — t        | «      S )z(Get the number of columns in the schema.)Úlenr+   s    r&   r1   z
Schema.lenj   s   € ä�4‹yÐr'   c               ó”   ‡ ‡— t        |t        «      r|s ‰ «       S ddl} |j                  |«      }ddlmŠ  ‰ ˆ ˆfd„|D «       «      S )a  Construct a Schema from a pyarrow Schema.

        Arguments:
            schema: A pyarrow Schema or mapping of column names to pyarrow data types.

        Examples:
            >>> import pyarrow as pa
            >>> import narwhals as nw
            >>>
            >>> mapping = {
            ...     "a": pa.timestamp("us", "UTC"),
            ...     "b": pa.date32(),
            ...     "c": pa.string(),
            ...     "d": pa.uint8(),
            ... }
            >>> native = pa.schema(mapping)
            >>>
            >>> nw.Schema.from_arrow(native)
            Schema({'a': Datetime(time_unit='us', time_zone='UTC'), 'b': Date, 'c': String, 'd': UInt8})

            >>> nw.Schema.from_arrow(mapping) == nw.Schema.from_arrow(native)
            True
        r   N©Únative_to_narwhals_dtypec              3  óp   •K  — | ]-  }|j                    ‰|j                  ‰j                  «      f–— Œ/ y ­wr    )ÚnameÚtyper   )Ú.0ÚfieldÚclsr4   s     €€r&   ú	<genexpr>z$Schema.from_arrow.<locals>.<genexpr>�   s2   øè ø€ ò 
àð �Z‰ZÑ1°%·*±*¸c¿l¹lÓKÔLñ
ùs   ƒ36)Ú
isinstancer   Úpyarrowr$   Únarwhals._arrow.utilsr4   )r:   r$   Úpar4   s   `  @r&   Ú
from_arrowzSchema.from_arrown   sI   ù€ ô2 �fœgÔ&ÙÙ“u�Û à�R—Y‘Y˜vÓ&ˆFÝBáô 
àô
ó 
ð 	
r'   c               óÌ   — |s | «       S t        «       r0t        d„ |j                  «       D «       «      rt        j                  nt        j
                  }| j                  ||«      S )a3  Construct a Schema from a pandas-like schema representation.

        Arguments:
            schema: A mapping of column names to pandas-like data types.

        Examples:
            >>> import numpy as np
            >>> import pandas as pd
            >>> import pyarrow as pa
            >>> import narwhals as nw
            >>>
            >>> data = {"a": [1], "b": ["a"], "c": [False], "d": [9.2]}
            >>> native = pd.DataFrame(data).convert_dtypes().dtypes.to_dict()
            >>>
            >>> nw.Schema.from_pandas_like(native)
            Schema({'a': Int64, 'b': String, 'c': Boolean, 'd': Float64})
            >>>
            >>> mapping = {
            ...     "a": pd.DatetimeTZDtype("us", "UTC"),
            ...     "b": pd.ArrowDtype(pa.date32()),
            ...     "c": pd.StringDtype("python"),
            ...     "d": np.dtype("uint8"),
            ... }
            >>>
            >>> nw.Schema.from_pandas_like(mapping)
            Schema({'a': Datetime(time_unit='us', time_zone='UTC'), 'b': Date, 'c': String, 'd': UInt8})
        c              3  ó2   K  — | ]  }t        |«      –— Œ y ­wr    )r   )r8   Údtypes     r&   r;   z*Schema.from_pandas_like.<locals>.<genexpr>µ   s   è ø€ Ò!T¸5¤-°×"6Ñ!Tùs   ‚)r   Úanyr.   r	   ÚCUDFÚPANDASÚ_from_pandas_like)r:   r$   Úimpls      r&   Úfrom_pandas_likezSchema.from_pandas_like”   sV   € ñ: Ù“5ˆLô ŒzœcÑ!TÀFÇMÁMÃOÔ!TÔTô ×Òä×&Ñ&ð 	ð
 ×$Ñ$ V¨TÓ2Ð2r'   c               óþ   — t        |«      r| j                  |«      S t        |«      r| j                  |«      S t	        |t
        «      r|r| j                  |«      S  | «       S dt        |«      ›d|›�}t        |«      ‚)ao  Construct a Schema from a native schema representation.

        Arguments:
            schema: A native schema object, or mapping of column names to
                *instantiated* native data types.

        Examples:
            >>> import datetime as dt
            >>> import pyarrow as pa
            >>> import narwhals as nw
            >>>
            >>> data = {"a": [1], "b": ["a"], "c": [dt.time(1, 2, 3)], "d": [[2]]}
            >>> native = pa.table(data).schema
            >>>
            >>> nw.Schema.from_native(native)
            Schema({'a': Int64, 'b': String, 'c': Time, 'd': List(Int64)})
        z5Expected an arrow, polars, or pandas schema, but got z

)	r   r@   r   Úfrom_polarsr<   r   Ú_from_native_mappingr   Ú	TypeError)r:   r$   Úmsgs      r&   Úfrom_nativezSchema.from_nativeº   s€   € ô* ˜VÔ$Ø—>‘> &Ó)Ð)Ü˜FÔ#Ø—?‘? 6Ó*Ð*Ü�fœgÔ&Ù7=�3×+Ñ+¨FÓ3ÐHÁ3Ã5ÐHàCÜ" 6Ó*Ð-¨T°&°ð=ð 	ô ˜‹nÐr'   c               ód   ‡ ‡— |s ‰ «       S ddl mŠ  ‰ ˆ ˆfd„|j                  «       D «       «      S )a/  Construct a Schema from a polars Schema.

        Arguments:
            schema: A polars Schema or mapping of column names to *instantiated*
                polars data types.

        Examples:
            >>> import polars as pl
            >>> import narwhals as nw
            >>>
            >>> mapping = {
            ...     "a": pl.Datetime(time_zone="UTC"),
            ...     "b": pl.Date(),
            ...     "c": pl.String(),
            ...     "d": pl.UInt8(),
            ... }
            >>> native = pl.Schema(mapping)
            >>>
            >>> nw.Schema.from_polars(native)
            Schema({'a': Datetime(time_unit='us', time_zone='UTC'), 'b': Date, 'c': String, 'd': UInt8})

            >>> nw.Schema.from_polars(mapping) == nw.Schema.from_polars(native)
            True
        r   r3   c              3  óN   •K  — | ]  \  }}| ‰|‰j                   «      f–— Œ y ­wr    ©r   )r8   r6   rC   r:   r4   s      €€r&   r;   z%Schema.from_polars.<locals>.<genexpr>ù   s.   øè ø€ ò 
á��eð Ñ+¨E°3·<±<Ó@ÔAñ
ùó   ƒ"%)Únarwhals._polars.utilsr4   Úitems)r:   r$   r4   s   ` @r&   rK   zSchema.from_polarsÛ   s2   ù€ ñ4 Ù“5ˆLÝCáô 
à%Ÿ|™|›~ô
ó 
ð 	
r'   c                ón   ‡ ‡— ddl }ddlmŠ  |j                  ˆˆ fd„‰ j	                  «       D «       «      S )a  Convert Schema to a pyarrow Schema.

        Examples:
            >>> import narwhals as nw
            >>> schema = nw.Schema({"a": nw.Int64(), "b": nw.Datetime("ns")})
            >>> schema.to_arrow()
            a: int64
            b: timestamp[ns]
        r   N©Únarwhals_to_native_dtypec              3  óN   •K  — | ]  \  }}| ‰|‰j                   «      f–— Œ y ­wr    rR   ©r8   r6   rC   rX   r#   s      €€r&   r;   z"Schema.to_arrow.<locals>.<genexpr>  s.   øè ø€ ò 
á��eð Ñ+¨E°4·=±=ÓAÔBñ
ùrS   )r=   r>   rX   r$   rU   )r#   r?   rX   s   ` @r&   Úto_arrowzSchema.to_arrowþ   s1   ù€ ó 	åBàˆr�y‰yô 
à#Ÿz™z›|ô
ó 
ð 	
r'   c                ó¤  — ddl m} t        |t        j                  | j
                  ¬«      }|�t        |t        «      r,| j                  «       D ��ci c]  \  }}| |||¬«      “Œ c}}S t        |«      }t        |«      t        | «      k7  rnddlm}m}m}	 t        |«      t        | «      }}
t         ||j                   | |	|«      |«      «      |«      «      }d|
›d|›d|› d	|d   › d
|› d�}t!        |«      ‚t#        | j%                  «       | j'                  «       |d¬«      D ���ci c]  \  }}}| |||¬«      “Œ c}}}S c c}}w c c}}}w )am  Convert Schema to an ordered mapping of column names to their pandas data type.

        Arguments:
            dtype_backend: Backend(s) used for the native types. When providing more than
                one, the length of the iterable must be equal to the length of the schema.

        Examples:
            >>> import narwhals as nw
            >>> schema = nw.Schema({"a": nw.Int64(), "b": nw.Datetime("ns")})
            >>> schema.to_pandas()
            {'a': 'int64', 'b': 'datetime64[ns]'}

            >>> schema.to_pandas("pyarrow")
            {'a': 'Int64[pyarrow]', 'b': 'timestamp[ns][pyarrow]'}
        r   rW   )ÚimplementationÚversion)rC   Údtype_backend)ÚchainÚisliceÚrepeatz	Provided z) `dtype_backend`(s), but schema contains z1 field(s).
Hint: instead of
    schema.to_pandas(z+)
you may want to use
    schema.to_pandas(z)
or
    schema.to_pandas(ú)T)Ústrict)Únarwhals._pandas_like.utilsrX   r   r	   rF   r   r<   ÚstrrU   Útupler1   Ú	itertoolsr`   ra   rb   Úfrom_iterableÚ
ValueErrorÚzipr*   r.   )r#   r_   rX   Úto_native_dtyper6   rC   Úbackendsr`   ra   rb   Ún_userÚn_actualÚ
suggestionrN   Úbackends                  r&   Ú	to_pandaszSchema.to_pandas  sk  € õ$ 	Iä!Ø$Ü)×0Ñ0Ø—M‘Mô
ˆð
 Ð ¤J¨}¼cÔ$Bð $(§:¡:£<÷á�D˜%ð ‘o¨EÀÔOÑOóð ô ˜Ó'ˆÜˆx‹=œC ›IÒ%ß7Ñ7ä" 8›}¬c°$«i�HˆFÜÙ�u×*Ñ*©6±&¸Ó2BÀHÓ+MÓNÐPXÓYóˆJð ˜F˜:Ð%NÈxÈlð [(à(0 zð 2(à(0°© }ð 5(à(2 |°1ð6ð ô ˜S“/Ð!ô ),Ø—	‘	“˜TŸ[™[›]¨H¸Tô)÷
ð 
á$��e˜Wð ‘/¨¸WÔEÑEô
ð 	
ùó-ùô,
s   ÁEÄ*Ec                óâ   ‡ ‡— ddl }ddlmŠ t        j                  j                  «       }ˆˆ fd„‰ j                  «       D «       }|dk\  r |j                  |«      S t        dt        |«      «      S )a%  Convert Schema to a polars Schema.

        Examples:
            >>> import narwhals as nw
            >>> schema = nw.Schema({"a": nw.Int64(), "b": nw.Datetime("ns")})
            >>> schema.to_polars()
            Schema({'a': Int64, 'b': Datetime(time_unit='ns', time_zone=None)})
        r   NrW   c              3  óN   •K  — | ]  \  }}| ‰|‰j                   «      f–— Œ y ­wr    rR   rZ   s      €€r&   r;   z#Schema.to_polars.<locals>.<genexpr>V  s.   øè ø€ ò 
á��eð Ñ+¨E°4·=±=ÓAÔBñ
ùrS   )é   r   r   ú	pl.Schema)
ÚpolarsrT   rX   r	   ÚPOLARSÚ_backend_versionrU   r   r   Údict)r#   ÚplÚ
pl_versionr$   rX   s   `   @r&   Ú	to_polarszSchema.to_polarsH  sh   ù€ ó 	åCä#×*Ñ*×;Ñ;Ó=ˆ
ô
à#Ÿz™z›|ô
ˆð ˜YÒ&ð ˆB�I‰I�fÓð	
ô �k¤4¨£<Ó0ð	
r'   c               ór  — t        t        |j                  «       «      «      }|\  }}t        |«      r| j	                  t        d|«      «      S t        |«      r| j                  t        d|«      «      S t        |«      r| j                  t        d|«      «      S d|› dt        |«      › d|›�}t        |«      ‚)Nr   r   r   z7Expected an arrow, polars, or pandas dtype, but found `z: z`

)ÚnextÚiterrU   r   rK   r   r   rI   r   r@   r   rM   )r:   ÚnativeÚ
first_itemÚ	first_keyÚfirst_dtyperN   s         r&   rL   zSchema._from_native_mapping`  s¶   € ô œ$˜vŸ|™|›~Ó.Ó/ˆ
Ø!+Ñˆ	�;Ü˜{Ô+Ø—?‘?¤4Ð(:¸FÓ#CÓDÐDÜ Ô,Ø×'Ñ'¬Ð-?ÀÓ(HÓIÐIÜ Ô,Ø—>‘>¤$Ð'8¸&Ó"AÓBÐBðØˆ{˜"Ô0°Ó=Ð>¸eÀFÀ:ðOð 	ô ˜‹nÐr'   c               óZ   ‡ ‡‡— ddl mŠ |Š ‰ ˆ ˆˆfd„|j                  «       D «       «      S )Nr   r3   c              3  óT   •K  — | ]  \  }}| ‰|‰j                   ‰d ¬«      f–— Œ! y­w)T)Úallow_objectNrR   )r8   r6   rC   r:   rH   r4   s      €€€r&   r;   z+Schema._from_pandas_like.<locals>.<genexpr>{  s3   øè ø€ ò 
á��eð Ñ+¨E°3·<±<ÀÐTXÔYÔZñ
ùs   ƒ%()re   r4   rU   )r:   r$   r]   rH   r4   s   `  @@r&   rG   zSchema._from_pandas_liket  s.   ú€ õ 	IàˆÙõ 
à%Ÿ|™|›~ô
ó 
ð 	
r'   r    )r$   z8Mapping[str, DType] | Iterable[tuple[str, DType]] | NoneÚreturnÚNone)rˆ   z	list[str])rˆ   zlist[DType])rˆ   Úint)r$   r   rˆ   r   )r$   r   rˆ   r   )r$   z5IntoArrowSchema | IntoPolarsSchema | IntoPandasSchemarˆ   r   )r$   r   rˆ   r   )rˆ   z	pa.Schema)r_   z%DTypeBackend | Iterable[DTypeBackend]rˆ   zdict[str, Any])rˆ   rv   )r�   zHMapping[str, pa.DataType] | Mapping[str, pl.DataType] | IntoPandasSchemarˆ   r   )r$   r   r]   r	   rˆ   r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r
   ÚMAINr   Ú__annotations__r"   r,   r/   r1   Úclassmethodr@   rI   rO   rK   r[   rr   r}   rL   rG   Ú__classcell__)r%   s   @r&   r   r   -   s"  ø… ñ"ðH #*§,¡,€HÐÓ.ð RVð!ØNð!à	õ!ó
!ó#óð ò#
ó ð#
ðJ ò#3ó ð#3ðJ ðØJðà	òó ðð@ ò 
ó ð 
óD
ð( FJð5
ØBð5
à	ó5
ón
ð0 ðàXðð 
ò	ó ðð& ð	
Ø%ð	
Ø7Eð	
à	ò	
ó ô	
r'   r   )+rŽ   Ú
__future__r   Úcollectionsr   Úcollections.abcr   Ú	functoolsr   Útypingr   r   Únarwhals._utilsr	   r
   r   Únarwhals.dependenciesr   r   r   r   r   r   r   r   r   r   rw   r{   r=   r?   Útyping_extensionsr   Únarwhals.dtypesr   Únarwhals.typingr   r   r   r   Ú__all__rf   r   © r'   r&   ú<module>rŸ      sq   ðñõ #å #Ý #Ý ß &ç HÑ H÷÷ ñ ñ Ý(ß$ãÛÝ&å%÷ó ð ˆ*€ôQ
ˆ[˜˜g˜Ñ&õ Q
r'   