o
    i9                     @  s   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 d dlmZ d dlmZ erfd dlZd d	lmZ d d
lmZ d dlmZ d dlmZmZ ejdkr`d dlm
Z
 nd dlm
Z
 G dd dZ dS )    )annotations)TYPE_CHECKINGLiteraloverloadN)
deprecated)serialize_polars_object)display_dot_graph	wrap_expr)ComputeError)IOBase)Path)Expr)
SchemaDictSerializationFormat)      c                   @  s  e Zd ZdZdZdmddZdnd
dZdnddZdoddZdpddZ	dpddZ
dpddZdpddZdqddZdqddZdqd d!Zd"d#drd%d&Zd"d#drd'd(Zed)d*dsd-d.Zedtd1d.Zd)d*dud2d.Zd3d4dvd8d9Zdwd;d<Zdxd=d>Zdxd?d@ZdydBdCZe	DdzdDdEd{dJdKZedzd|dMdKZedDdEd}dPdKZ	3d~dQdEddTdKZedzddUdVZeddWdVZedXd~ddYdVZedDd3dZdd]d^Zed3d4dd_d^Zd"d3dZdd`d^Zd)d3d"dad3dbddidjZddkdlZd3S )ExprMetaNameSpacez*Namespace for expressions on a meta level.metaexprr   returnNonec                 C  s   |j | _ d S N)_pyexprselfr    r   G/home/app/Keep/.python/lib/python3.10/site-packages/polars/expr/meta.py__init__   s   zExprMetaNameSpace.__init__strc                 C     t | j  dS Nz.meta)r
   r   __str__r   r   r   r   r"   "      zExprMetaNameSpace.__str__c                 C  r    r!   )r
   r   __repr__r#   r   r   r   r%   %   r$   zExprMetaNameSpace.__repr__intc                 C  
   | j  S r   )r   __hash__r#   r   r   r   r(   (      
zExprMetaNameSpace.__hash__otherExprMetaNameSpace | Exprboolc                 C     | j |j S r   r   Zmeta_eqr   r*   r   r   r   __eq__+   s   zExprMetaNameSpace.__eq__c                 C  s
   | |k S r   r   r/   r   r   r   __ne__.   r)   zExprMetaNameSpace.__ne__c                 C  r-   )aX  
        Indicate if this expression is the same as another expression.

        Examples
        --------
        >>> foo_bar = pl.col("foo").alias("bar")
        >>> foo = pl.col("foo")
        >>> foo_bar.meta.eq(foo)
        False
        >>> foo_bar2 = pl.col("foo").alias("bar")
        >>> foo_bar.meta.eq(foo_bar2)
        True
        r.   r/   r   r   r   eq1   s   zExprMetaNameSpace.eqc                 C  s   |  | S )a\  
        Indicate if this expression is NOT the same as another expression.

        Examples
        --------
        >>> foo_bar = pl.col("foo").alias("bar")
        >>> foo = pl.col("foo")
        >>> foo_bar.meta.ne(foo)
        True
        >>> foo_bar2 = pl.col("foo").alias("bar")
        >>> foo_bar.meta.ne(foo_bar2)
        False
        )r2   r/   r   r   r   neA   s   zExprMetaNameSpace.nec                 C  r'   )z
        Indicate if this expression expands into multiple expressions.

        Examples
        --------
        >>> e = pl.col(["a", "b"]).name.suffix("_foo")
        >>> e.meta.has_multiple_outputs()
        True
        )r   Zmeta_has_multiple_outputsr#   r   r   r   has_multiple_outputsQ      

z&ExprMetaNameSpace.has_multiple_outputsc                 C  r'   )aq  
        Indicate if this expression is a basic (non-regex) unaliased column.

        Examples
        --------
        >>> e = pl.col("foo")
        >>> e.meta.is_column()
        True
        >>> e = pl.col("foo") * pl.col("bar")
        >>> e.meta.is_column()
        False
        >>> e = pl.col(r"^col.*\d+$")
        >>> e.meta.is_column()
        False
        )r   Zmeta_is_columnr#   r   r   r   	is_column]   s   
zExprMetaNameSpace.is_columnc                 C  r'   )z
        Indicate if this expression expands to columns that match a regex pattern.

        Examples
        --------
        >>> e = pl.col("^.*$").name.prefix("foo_")
        >>> e.meta.is_regex_projection()
        True
        )r   Zmeta_is_regex_projectionr#   r   r   r   is_regex_projectiono   r5   z%ExprMetaNameSpace.is_regex_projectionF)allow_aliasingr8   c                C     | j |S )az  
        Indicate if this expression only selects columns (optionally with aliasing).

        This can include bare columns, columns matched by regex or dtype, selectors
        and exclude ops, and (optionally) column/expression aliasing.

        .. versionadded:: 0.20.30

        Parameters
        ----------
        allow_aliasing
            If False (default), any aliasing is not considered to be column selection.
            Set True to allow for column selection that also includes aliasing.

        Examples
        --------
        >>> import polars.selectors as cs
        >>> e = pl.col("foo")
        >>> e.meta.is_column_selection()
        True
        >>> e = pl.col("foo").alias("bar")
        >>> e.meta.is_column_selection()
        False
        >>> e.meta.is_column_selection(allow_aliasing=True)
        True
        >>> e = pl.col("foo") * pl.col("bar")
        >>> e.meta.is_column_selection()
        False
        >>> e = cs.starts_with("foo")
        >>> e.meta.is_column_selection()
        True
        >>> e = cs.starts_with("foo").exclude("foo!")
        >>> e.meta.is_column_selection()
        True
        )r   Zmeta_is_column_selectionr   r8   r   r   r   is_column_selection{   s   $z%ExprMetaNameSpace.is_column_selectionc                C  r9   )a  
        Indicate if this expression is a literal value (optionally aliased).

        .. versionadded:: 1.14

        Parameters
        ----------
        allow_aliasing
            If False (default), only a bare literal will match.
            Set True to also allow for aliased literals.

        Examples
        --------
        >>> from datetime import datetime
        >>> e = pl.lit(123)
        >>> e.meta.is_literal()
        True
        >>> e = pl.lit(987.654321).alias("foo")
        >>> e.meta.is_literal()
        False
        >>> e = pl.lit(datetime.now()).alias("bar")
        >>> e.meta.is_literal(allow_aliasing=True)
        True
        )r   Zmeta_is_literalr:   r   r   r   
is_literal   s   zExprMetaNameSpace.is_literalT)raise_if_undeterminedr=   Literal[True]c                C     d S r   r   r   r=   r   r   r   output_name      zExprMetaNameSpace.output_nameLiteral[False]
str | Nonec                C  r?   r   r   r@   r   r   r   rA      rB   c                C  s(   z| j  W S  ty   |sY dS  w )aa  
        Get the column name that this expression would produce.

        It may not always be possible to determine the output name as that can depend
        on the schema of the context; in that case this will raise `ComputeError` if
        `raise_if_undetermined` is True (the default), or `None` otherwise.

        Examples
        --------
        >>> e = pl.col("foo") * pl.col("bar")
        >>> e.meta.output_name()
        'foo'
        >>> e_filter = pl.col("foo").filter(pl.col("bar") == 13)
        >>> e_filter.meta.output_name()
        'foo'
        >>> e_sum_over = pl.sum("foo").over("groups")
        >>> e_sum_over.meta.output_name()
        'foo'
        >>> e_sum_slice = pl.sum("foo").slice(pl.len() - 10, pl.col("bar"))
        >>> e_sum_slice.meta.output_name()
        'foo'
        >>> pl.len().meta.output_name()
        'len'
        N)r   Zmeta_output_namer   r@   r   r   r   rA      s   N)schemarE   SchemaDict | None
list[Expr]c                C  s   dd | j |D S )a<  
        Pop the latest expression and return the input(s) of the popped expression.

        Returns
        -------
        list of Expr
            A list of expressions which in most cases will have a unit length.
            This is not the case when an expression has multiple inputs.
            For instance in a `fold` expression.

        Examples
        --------
        >>> e = pl.col("foo") + pl.col("bar")
        >>> first = e.meta.pop()[0]
        >>> first.meta == pl.col("bar")
        True
        >>> first.meta == pl.col("foo")
        False
        c                 S  s   g | ]}t |qS r   r	   ).0er   r   r   
<listcomp>   s    z)ExprMetaNameSpace.pop.<locals>.<listcomp>)r   Zmeta_pop)r   rE   r   r   r   pop   s   zExprMetaNameSpace.pop	list[str]c                 C  r'   )aD  
        Get a list with the root column name.

        Examples
        --------
        >>> e = pl.col("foo") * pl.col("bar")
        >>> e.meta.root_names()
        ['foo', 'bar']
        >>> e_filter = pl.col("foo").filter(pl.col("bar") == 13)
        >>> e_filter.meta.root_names()
        ['foo', 'bar']
        >>> e_sum_over = pl.sum("foo").over("groups")
        >>> e_sum_over.meta.root_names()
        ['foo', 'groups']
        >>> e_sum_slice = pl.sum("foo").slice(pl.len() - 10, pl.col("bar"))
        >>> e_sum_slice.meta.root_names()
        ['foo', 'bar']
        )r   Zmeta_root_namesr#   r   r   r   
root_names   s   
zExprMetaNameSpace.root_namesc                 C  s   t | j S )aR  
        Undo any renaming operation like `alias` or `name.keep`.

        Examples
        --------
        >>> e = pl.col("foo").alias("bar")
        >>> e.meta.undo_aliases().meta == pl.col("foo")
        True
        >>> e = pl.col("foo").sum().over("bar")
        >>> e.name.keep().meta.undo_aliases().meta == e
        True
        )r
   r   Zmeta_undo_aliasesr#   r   r   r   undo_aliases  s   zExprMetaNameSpace.undo_aliasesc                 C  s
   t | jS )zReturn the original expression.)r
   r   r#   r   r   r   as_expression  s   
zExprMetaNameSpace.as_expressionpl.Selectorc                 C  s   t j| j S )a2  
        Try to turn this expression in a selector.

        Raises if the underlying expressions is not a column or selector.

        .. warning::
            This functionality is considered **unstable**. It may be changed
            at any point without it being considered a breaking change.
        )plZSelectorZ_from_pyselectorr   Zinto_selectorr#   r   r   r   as_selector   s   
zExprMetaNameSpace.as_selector.formatfilerT   Literal['binary']bytesc                C  r?   r   r   r   rU   rT   r   r   r   	serialize,     zExprMetaNameSpace.serializeLiteral['json']c                C  r?   r   r   rX   r   r   r   rY   1  rB   IOBase | str | Pathr   c                C  r?   r   r   rX   r   r   r   rY   4  rZ   binaryIOBase | str | Path | Nonebytes | str | Nonec                C  sB   |dkr	| j j}n|dkr| j j}n	d|}t|t|||S )u  
        Serialize this expression to a file or string in JSON format.

        Parameters
        ----------
        file
            File path to which the result should be written. If set to `None`
            (default), the output is returned as a string instead.
        format
            The format in which to serialize. Options:

            - `"binary"`: Serialize to binary format (bytes). This is the default.
            - `"json"`: Serialize to JSON format (string).

        See Also
        --------
        Expr.deserialize

        Notes
        -----
        Serialization is not stable across Polars versions: a LazyFrame serialized
        in one Polars version may not be deserializable in another Polars version.

        Examples
        --------
        Serialize the expression into a binary representation.

        >>> expr = pl.col("foo").sum().over("bar")
        >>> bytes = expr.meta.serialize()
        >>> type(bytes)
        <class 'bytes'>

        The bytes can later be deserialized back into an `Expr` object.

        >>> import io
        >>> pl.Expr.deserialize(io.BytesIO(bytes))
        <Expr ['col("foo").sum().over([col("ba…'] at ...>
        r]   jsonz0`format` must be one of {'binary', 'json'}, got )r   Zserialize_binaryZserialize_json
ValueErrorr   )r   rU   rT   
serializermsgr   r   r   rY   9  s   ,


c                 C  r?   r   r   r   rU   r   r   r   
write_jsono  rB   zExprMetaNameSpace.write_jsonc                 C  r?   r   r   rd   r   r   r   re   r  rB   z;`meta.write_json` was renamed; use `meta.serialize` insteadc                 C  s   | j |ddS )z
        Write expression to json.

        .. deprecated:: 0.20.11
            This method has been renamed to :meth:`serialize`.
        r`   rS   )rY   rd   r   r   r   re   u  s   )return_as_stringrE   rf   None | SchemaDictc                C  r?   r   r   r   rf   rE   r   r   r   tree_format  s   zExprMetaNameSpace.tree_formatc                C  r?   r   r   rh   r   r   r   ri     rZ   c                C  s    | j |}|r
|S t| dS )am  
        Format the expression as a tree.

        Parameters
        ----------
        return_as_string:
            If True, return as string rather than printing to stdout.
        schema
            Optionally provide a schema for the expression tree formatter.
            This is a mapping of column names to their data types. If provided,
            it may be used to enhance the tree formatting with type information.

        Examples
        --------
        >>> e = (pl.col("foo") * pl.col("bar")).sum().over(pl.col("ham")) / 2
        >>> e.meta.tree_format(return_as_string=True)  # doctest: +SKIP
        N)r   Zmeta_tree_formatprint)r   rf   rE   sr   r   r   ri     s
   )g      0@g      (@)showoutput_path
raw_outputfigsizerE   rl   rm   str | Path | Nonern   ro   tuple[float, float]c                C  s   | j |}t|||||dS )a  
        Format the expression as a Graphviz graph.

        Note that Graphviz must be installed to render the visualization (if not
        already present, you can download it here: `<https://graphviz.org/download>`_).

        Parameters
        ----------
        show
            Show the figure.
        output_path
            Write the figure to disk.
        raw_output
            Return dot syntax. This cannot be combined with `show` and/or `output_path`.
        figsize
            Passed to matplotlib if `show == True`.
        schema
            Optionally provide a schema for the expression tree formatter.
            This is a mapping of column names to their data types. If provided,
            it may be used to enhance the tree formatting with type information.

        Examples
        --------
        >>> e = (pl.col("foo") * pl.col("bar")).sum().over(pl.col("ham")) / 2
        >>> e.meta.show_graph()  # doctest: +SKIP
        )dotrl   rm   rn   ro   )r   Zmeta_show_graphr   )r   rl   rm   rn   ro   rE   rr   r   r   r   
show_graph  s   #zExprMetaNameSpace.show_graphc                 C  s   t | j|jS r   )r
   r   Zmeta_replace_elementr   r   r   r   _replace_element  s   z"ExprMetaNameSpace._replace_element)r   r   r   r   )r   r   )r   r&   )r*   r+   r   r,   )r   r,   )r8   r,   r   r,   )r=   r>   r   r   )r=   rC   r   rD   )r=   r,   r   rD   )rE   rF   r   rG   )r   rL   )r   r   )r   rP   ).)rU   r   rT   rV   r   rW   )rU   r   rT   r[   r   r   )rU   r\   rT   r   r   r   r   )rU   r^   rT   r   r   r_   )rU   r   r   r   )rU   r\   r   r   )rU   r^   r   rD   )rf   rC   rE   rg   r   r   )rf   r>   rE   rg   r   r   )rf   r,   rE   rg   r   rD   )rl   r,   rm   rp   rn   r,   ro   rq   rE   rg   r   rD   )r   r   r   r   )__name__
__module____qualname____doc__	_accessorr   r"   r%   r(   r0   r1   r2   r3   r4   r6   r7   r;   r<   r   rA   rK   rM   rN   rO   rR   rY   re   r   ri   rs   rt   r   r   r   r   r      s|    










& 



6	,r   )!
__future__r   typingr   r   r   Zpolars._reexportZ	_reexportrQ   Zpolars._utils.deprecationr   Zpolars._utils.serder   Zpolars._utils.variousr   Zpolars._utils.wrapr
   Zpolars.exceptionsr   sysior   pathlibr   Zpolarsr   Zpolars._typingr   r   version_infowarningsZtyping_extensionsr   r   r   r   r   <module>   s$    
