
    AHj'                       U d dl m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 dlmZ d dlmZ d dl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  ej8                  e      5  d dlmZm Z m!Z! ddd       er?d dl"Z"d dlm#Z# d dlm$Z$ e"jJ                  dk\  rd dlm&Z& nd dl'm&Z& d dl(Z)d dl*m+Z+m,Z, d dlm-Z- nd dl.m(Z) ddZ/ee0ef   Z1eez  ez  Z2de3d<   dgZ4ddZ5ddZ6 G d de1      Z7y# 1 sw Y   xY w)    )annotationsN)OrderedDict)Mapping)TYPE_CHECKINGAnyLiteraloverload)PythonDataType)unstable)DataTypeDataTypeClassis_polars_dtype)parse_into_dtype)unpack_dtypes)DuplicateError)CompatLevel)&init_polars_schema_from_arrow_c_schema'polars_schema_field_from_arrow_c_schemapolars_schema_to_pycapsule)Iterable)	TypeAlias)      )TypeIs	DataFrame	LazyFrame)ArrowSchemaExportable)pyarrowc                ,    t        | j                        S N)bool__annotations__)tps    E/root/tools/cai/cai_env/lib/python3.12/site-packages/polars/schema.py_required_init_argsr&   )   s    ""##    r   SchemaInitDataTypeSchemac                    t        | t              sB| j                         s| j                         st	        |       rd| }t        |       |        } | S )Nz%dtypes must be fully-specified, got: )
isinstancer   	is_nested
is_decimalr&   	TypeError)r$   msgs     r%   _check_dtyper0   3   sG    b(#<<>R]]_0CB0G9"@CC. TIr'   c                    t        | d      S )N__arrow_c_schema__)hasattr)objs    r%   _is_arrow_schema_exportabler5   =   s    3,--r'   c                       e Zd ZdZ	 ddd	 	 	 	 	 d fdZddZddZ	 	 	 	 	 	 d fdZ e       dd	       Z	dd
Z
ddZ e       dddd       Zedd       Zedddd       Zddd dZd!dZd"dZd#dZ xZS )$r)   aA  
    Ordered mapping of column names to their data type.

    Parameters
    ----------
    schema
        The schema definition given by column names and their associated
        Polars data type. Accepts a mapping, or an iterable of tuples, or any
        object implementing the  `__arrow_c_schema__` PyCapsule interface
        (e.g. pyarrow schemas).

    Examples
    --------
    Define a schema by passing instantiated data types.

    >>> schema = pl.Schema(
    ...     {
    ...         "foo": pl.String(),
    ...         "bar": pl.Duration("us"),
    ...         "baz": pl.Array(pl.Int8, 4),
    ...     }
    ... )
    >>> schema
    Schema({'foo': String, 'bar': Duration(time_unit='us'), 'baz': Array(Int8, shape=(4,))})

    Access the data type associated with a specific column name.

    >>> schema["baz"]
    Array(Int8, shape=(4,))

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

    >>> schema.names()
    ['foo', 'bar', 'baz']
    >>> schema.dtypes()
    [String, Duration(time_unit='us'), Array(Int8, shape=(4,))]
    >>> schema.len()
    3

    Import a pyarrow schema.

    >>> import pyarrow as pa
    >>> pl.Schema(pa.schema([pa.field("x", pa.int32())]))
    Schema({'x': Int32})

    Export a schema to pyarrow.

    >>> pa.schema(pl.Schema({"x": pl.Int32}))
    x: int32
    NT)check_dtypesc                  t        |      rt        |t              st        | |       y t        |t              r|j                         n|xs d}|D ]o  }t        |      rt        |      n|\  }}|| v rd| d}t        |      |st        | %  ||       Ft        |      rt        | %  |t        |             k|| |<   q y )N z7iterable passed to pl.Schema contained duplicate name '')r5   r+   r)   r   r   itemsr   r   super__setitem__r   r0   )	selfschemar7   inputvnamer$   r/   	__class__s	           r%   __init__zSchema.__init__u   s     'v.z&&7Q24@
 #-VW"=FLb 	 A /q1 8: D" t|OPTvUVW$S))#D"- $#D,r*:;T
!	 r'   c                    t        |t              syt        |       t        |      k7  ryt        | j	                         |j	                         d      D ]#  \  \  }}\  }}||k7  s|j                  |      r# y y)NFT)strict)r+   r   lenzipr;   is_)r>   othernm1tp1nm2tp2s         r%   __eq__zSchema.__eq__   sl    %)t9E
"&)$**,d&S 	"JS#
ccz	 r'   c                &    | j                  |       S r!   )rO   )r>   rJ   s     r%   __ne__zSchema.__ne__   s    ;;u%%%r'   c                N    t        t        |            }t        |   ||       y r!   )r0   r   r<   r=   )r>   rB   dtyperC   s      r%   r=   zSchema.__setitem__   s$     -e45D%(r'   c                R    t        | t        j                         j                        S )z
        Export a Schema via the Arrow PyCapsule Interface.

        https://arrow.apache.org/docs/dev/format/CDataInterface/PyCapsuleInterface.html
        )r   r   newest_versionr>   s    r%   r2   zSchema.__arrow_c_schema__   s      *$0B0B0D0M0MNNr'   c                4    t        | j                               S )z
        Get the column names of the schema.

        Examples
        --------
        >>> s = pl.Schema({"x": pl.Float64(), "y": pl.Datetime(time_zone="UTC")})
        >>> s.names()
        ['x', 'y']
        )listkeysrW   s    r%   nameszSchema.names   s     DIIK  r'   c                4    t        | j                               S )z
        Get the data types of the schema.

        Examples
        --------
        >>> s = pl.Schema({"x": pl.UInt8(), "y": pl.List(pl.UInt8)})
        >>> s.dtypes()
        [UInt8, List(UInt8)]
        )rY   valuesrW   s    r%   dtypeszSchema.dtypes   s     DKKM""r'   )compat_levelc                    G d d      }t        j                   || |t        j                                     S |            S )aI  
        Convert the schema to a pyarrow schema.

        Parameters
        ----------
        compat_level
            Use a specific compatibility level
            when exporting Polars' internal data types.

        Examples
        --------
        >>> pl.Schema({"x": pl.String}).to_arrow()
        x: string_view
        c                      e Zd ZddZddZy).Schema.to_arrow.<locals>.SchemaCapsuleProviderc                     || _         || _        y r!   )r?   r_   )r>   r?   r_   s      r%   rD   z7Schema.to_arrow.<locals>.SchemaCapsuleProvider.__init__   s    $$0!r'   c                V    t        | j                  | j                  j                        S r!   )r   r?   r_   rV   rW   s    r%   r2   zASchema.to_arrow.<locals>.SchemaCapsuleProvider.__arrow_c_schema__   s$    1KK!2!2!;!; r'   N)r?   r)   r_   r   returnNonere   object)__name__
__module____qualname__rD   r2   r9   r'   r%   SchemaCapsuleProviderrb      s    1r'   rl   )par?   r   rU   )r>   r_   rl   s      r%   to_arrowzSchema.to_arrow   sL    "	 	 yy!l.Bk((*
 	
HT
 	
r'   c                    y r!   r9   r>   eagers     r%   to_framezSchema.to_frame   s    ?Br'   .)rq   c                    y r!   r9   rp   s     r%   rr   zSchema.to_frame   s    DGr'   c               :    ddl m}m} |r	 ||       S  ||       S )u  
        Create an empty DataFrame (or LazyFrame) from this Schema.

        Parameters
        ----------
        eager
            If True, create a DataFrame; otherwise, create a LazyFrame.

        Examples
        --------
        >>> s = pl.Schema({"x": pl.Int32(), "y": pl.String()})
        >>> s.to_frame()
        shape: (0, 2)
        ┌─────┬─────┐
        │ x   ┆ y   │
        │ --- ┆ --- │
        │ i32 ┆ str │
        ╞═════╪═════╡
        └─────┴─────┘
        >>> s.to_frame(eager=False)  # doctest: +IGNORE_RESULT
        <LazyFrame at 0x11BC0AD80>
        r   r   )r?   )polarsr   r   )r>   rq   r   r   s       r%   rr   zSchema.to_frame   s    . 	0).y%JIT4JJr'   c                    t        |       S )z
        Get the number of schema entries.

        Examples
        --------
        >>> s = pl.Schema({"x": pl.Int32(), "y": pl.List(pl.String)})
        >>> s.len()
        2
        >>> len(s)
        2
        )rG   rW   s    r%   rG   z
Schema.len  s     4yr'   c                r    | j                         D ci c]  \  }}||j                          c}}S c c}}w )a  
        Return a dictionary of column names and Python types.

        Examples
        --------
        >>> s = pl.Schema(
        ...     {
        ...         "x": pl.Int8(),
        ...         "y": pl.String(),
        ...         "z": pl.Duration("us"),
        ...     }
        ... )
        >>> s.to_python()
        {'x': <class 'int'>, 'y':  <class 'str'>, 'z': <class 'datetime.timedelta'>}
        )r;   	to_python)r>   rB   r$   s      r%   rx   zSchema.to_python  s-      6:ZZ\Brblln$BBBs   3c               |    |s"t        fd| j                         D              S t        | j                          v S )av  
        Check if the schema contains the given data type.

        Parameters
        ----------
        dtype
            The data type to search for.
        recursive
            If False, only check top-level column dtypes.
            If True, also search within nested types (List, Array, Struct).

        Examples
        --------
        >>> s = pl.Schema({"x": pl.Int64(), "y": pl.List(pl.Float64)})
        >>> s.contains_dtype(pl.Int64, recursive=False)
        True
        >>> s.contains_dtype(pl.Float64, recursive=False)
        False
        >>> s.contains_dtype(pl.Float64, recursive=True)
        True
        c              3  (   K   | ]	  }|k(    y wr!   r9   ).0dtrS   s     r%   	<genexpr>z(Schema.contains_dtype.<locals>.<genexpr>G  s     ;rrU{;s   )anyr]   r   )r>   rS   	recursives    ` r%   contains_dtypezSchema.contains_dtype0  s5    , ;T[[];;;M4;;=999r'   r!   )r?   zMapping[str, SchemaInitDataType] | Iterable[tuple[str, SchemaInitDataType] | ArrowSchemaExportable] | ArrowSchemaExportable | Noner7   r"   re   rf   )rJ   rh   re   r"   )rB   strrS   z)DataType | DataTypeClass | PythonDataTypere   rf   rg   )re   z	list[str])re   zlist[DataType])r_   zCompatLevel | Nonere   z	pa.Schema)rq   zLiteral[False]re   r   )rq   zLiteral[True]re   r   )rq   r"   re   zDataFrame | LazyFrame)re   int)re   zdict[str, type])rS   r   r   r"   re   r"   )ri   rj   rk   __doc__rD   rO   rQ   r=   r   r2   r[   r^   rn   r	   rr   rG   rx   r   __classcell__)rC   s   @r%   r)   r)   A   s    1t #  "# #  #  
# J&)) I)	) ZO O
!
# Z=A 
 
@ B B14G G(, K6C$:r'   )r$   r   re   r"   )r$   zDataType | DataTypeClassre   r   )r4   r   re   zTypeIs[ArrowSchemaExportable])8
__future__r   
contextlibcollectionsr   collections.abcr   typingr   r   r   r	   polars._typingr
   polars._utils.unstabler   polars.datatypesr   r   r   polars.datatypes._parser   polars.datatypes.convertr   polars.exceptionsr   polars.interchange.protocolr   suppressImportErrorpolars._plrr   r   r   sysr   r   version_infor   typing_extensionsr   rm   ru   r   r   r   polars._dependenciesr&   r   
BaseSchemar(   r#   __all__r0   r5   r)   r9   r'   r%   <module>r      s    "  # # 8 8 ) + E E 4 2 , 3Z%   ( 
7"!,+42$ h'
 (= 8> I I I*.H:Z H:c s   $C--C6