
    g+                    
   U 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 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r~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 d dlmZ d dlmZ d dlmZ ee   ez  ez  Zde d<    edee         Z! edeeef         Z" ede      Z# ede      Z$ ed      Z%	 	 	 	 	 	 d0dZ&	 	 	 	 	 	 	 	 d1dZ'	 	 	 	 	 	 d2d Z(	 	 	 	 	 	 	 	 d3d!Z)	 	 	 	 	 	 d4d"Z*	 	 	 	 	 	 d5d#Z+e
d$d%	 	 	 	 	 	 	 	 	 d6d&       Z,e
d$d%	 	 	 	 	 	 	 	 	 d7d'       Z,d$d%	 	 	 	 	 	 	 	 	 d8d(Z,e
	 	 	 	 	 	 	 	 	 	 d9d)       Z-e
	 	 	 	 	 	 	 	 	 	 d:d*       Z-	 	 	 	 	 	 	 	 	 	 d;d+Z-d<d,Z.d=d-Z/d=d.Z0y/)>    )annotations)copy)TYPE_CHECKING)Any)Sequence)TypeVar)Union)cast)overload)is_numpy_array)InvalidIntoExprError)Implementation)	TypeAlias)	ArrowExpr)PandasLikeExpr)CompliantDataFrame)CompliantExpr)CompliantLazyFrame)CompliantNamespace)CompliantSeries)CompliantSeriesT_cor   IntoCompliantExprCompliantExprT)boundArrowOrPandasLikeExprPandasLikeExprT
ArrowExprTTc                H    t        || j                               } ||       S )zReturn list of raw columns.	namespace)parse_into_expr__narwhals_namespace__)df	into_exprexprs      Q/var/www/openai/venv/lib/python3.12/site-packages/narwhals/_expression_parsing.pyevaluate_into_exprr(   -   s"    
 90I0I0KLD8O    c                     fd|D        D cg c]  }|D ]  }|  }}}|j                         D ]Q  \  }}t         |      }t        |      dkD  rd}	t        |	      |d   j	                  |      }
|j                  |
       S |S c c}}w )zEvaluate each expr into Series.c              3  6   K   | ]  }t        |        y wN)r(   ).0r%   r$   s     r'   	<genexpr>z&evaluate_into_exprs.<locals>.<genexpr>>   s     Q5i*2y95s      z-Named expressions must return a single columnr   )itemsr(   lenAssertionErroraliasappend)r$   exprsnamed_exprssublistitemseriesnamer&   evaluated_exprmsg	to_appends   `          r'   evaluate_into_exprsr>   6   s     R5QQGD 	 	Q  
 "'')
d+B5~"AC %%"1%++D1	i  * Ms   B	c                F    t        |d      rt        d|      } ||       S |S )zAEvaluate `expr` if it's an expression, otherwise return it as is.__narwhals_expr__CompliantExpr[Any])hasattrr
   )r$   r&   compliant_exprs      r'   maybe_evaluate_exprrD   K   s,     t()2D9b!!Kr)   c           	         |D cg c]  }t        ||        c}|j                         D cg c]!  \  }}t        ||       j                  |      # c}}z   S c c}w c c}}w )znParse each input as an expression (if it's not already one).

    See `parse_into_expr` for more details.
    r    )r"   r0   r3   )r!   r5   r6   r%   r:   r&   s         r'   parse_into_exprsrF   U   sn     NSSU	OI;US%++-W-JD$ 		288>-W  S Ws
   A&Ac               0   t        | d      r| S t        | d      r|j                  |       S t        | t              r|j	                  |       S t        |       r"|j                  |       }|j                  |      S t        j                  t        |             )a  Parse `into_expr` as an expression.

    For example, in Polars, we can do both `df.select('a')` and `df.select(pl.col('a'))`.
    We do the same in Narwhals:

    - if `into_expr` is already an expression, just return it
    - if it's a Series, then convert it to an expression
    - if it's a numpy array, then convert it to a Series and then to an expression
    - if it's a string, then convert it to an expression
    - else, raise
    r@   __narwhals_series__)
rB   _create_expr_from_series
isinstancestrcolr   _create_compliant_seriesr   from_invalid_typetype)r%   r!   r9   s      r'   r"   r"   d   s      y-.y/011)<<)S!}}Y''i 33I>11&99

0
0i
AAr)   c                J   t        | j                        }| j                  }t        |j	                               D ]N  }|Dt        || j                        r.|j                  |j                  |j                         Cd}d} n|Ld} n ||||d}t        |      ||fS )a  Return new root and output names after chaining expressions.

    Try tracking root and output names by combining them from all expressions appearing in kwargs.
    If any anonymous expression appears (e.g. nw.all()), then give up on tracking root names
    and just set it to None.
    Nz_Safety assertion failed, please report a bug to https://github.com/narwhals-dev/narwhals/issues)	r   _root_names_output_nameslistvaluesrJ   	__class__extendr2   )r&   kwargs
root_namesoutput_namesargr<   s         r'   infer_new_root_output_namesr[      s     d&&'J%%LFMMO$!jdnn&E*!!#//2!
#L % 
	*"4$)?oS!!|##r)   F)returns_scalarc                    y r,    r&   attrr\   rW   s       r'   reuse_series_implementationra      s     r)   c                    y r,   r^   r_   s       r'   ra   ra      s     r)   c          	           j                         d fd}t         fi \  }}j                  | j                  dz    j                   d ||i  j
                        S )a  Reuse Series implementation for expression.

    If Series.foo is already defined, and we'd like Expr.foo to be the same, we can
    leverage this method to do that for us.

    Arguments:
        expr: expression object.
        attr: name of method.
        returns_scalar: whether the Series version returns a scalar. In this case,
            the expression version should return a 1-row Series.
        args: arguments to pass to function.
        kwargs: keyword arguments to pass to function.
    c           
     <   j                         D ci c]  \  }}|t        | |       }}}r 
j                  t        j                  u rddini } 
|       D cg c];  }r%j                   t        |	      di |||      n t        |	      di |= }}
j                  \|D cg c]  }|j                   c}
j                  k7  r5d
j                   d|D cg c]  }|j                   c} }t        |      |S c c}}w c c}w c c}w c c}w )N_return_py_scalarF)reference_serieszySafety assertion failed, please report a bug to https://github.com/narwhals-dev/narwhals/issues
Expression output names: z
Series names: r^   )
r0   rD   _implementationr   PYARROW_create_series_from_scalargetattrrR   r:   r2   )r$   arg_name	arg_value_kwargsextra_kwargsr9   outsr<   r`   r&   rW   plxr\   s            r'   funcz)reuse_series_implementation.<locals>.func   sl    (.||~
'5#) )"i88'5 	 
 $"6"6.:P:P"P !%( 	 r(&
 # 	 **%%@@@!' + 
 '&112 # 	 &
 ) !SQVVS!T%7%77,,0,>,>+? @!25!6#Q!&&#!6 79 
 !%%
?
&
 "
 "7s   D	A D/D$D
r/   ->depthfunction_namerX   rY   rW   )r$   r   returnzSequence[CompliantSeries])r#   r[   _create_expr_from_callable_depth_function_namerm   )r&   r`   r\   rW   rr   rX   rY   rq   s   ````   @r'   ra   ra      s    ( 
%
%
'C   D  ;4J6JJ))kkAo,,-Rv6!)$,,)&) *  r)   c                     y r,   r^   r&   series_namespacer`   rW   s       r'   %reuse_series_namespace_implementationr~      s     r)   c                     y r,   r^   r|   s       r'   r~   r~      s     r)   c           	           j                         }|j                   fd j                  dz    j                   d d  j                   j
                  i  j                        S )a  Reuse Series implementation for expression.

    Just like `reuse_series_implementation`, but for e.g. `Expr.dt.foo` instead
    of `Expr.foo`.

    Arguments:
        expr: expression object.
        series_namespace: The Series namespace (e.g. `dt`, `cat`, `str`, `list`, `name`)
        attr: name of method.
        args: arguments to pass to function.
        kwargs: keyword arguments to pass to function.
    c           
     n     |       D cg c]  } t        t        |            di   c}S c c}w )Nr^   )rj   )r$   r9   r`   r&   rW   r}   s     r'   <lambda>z7reuse_series_namespace_implementation.<locals>.<lambda>  s@    r(
" =GGF$45t<FvF"
 
s   #2r/   rs   .rt   )r#   rx   ry   rz   rQ   rR   rm   )r&   r}   r`   rW   rq   s   ```` r'   r~   r~      s}    $ 
%
%
'C))	
 kkAo,,-R0@/A4&I##'')$,,)&) * 
 
r)   c                     | j                   dk  S )a(  Check if expr is a very simple one.

    Examples:
        - nw.col('a').mean()  # depth 1
        - nw.mean('a')  # depth 1
        - nw.len()  # depth 0

    as opposed to, say

        - nw.col('a').filter(nw.col('b')>nw.col('c')).max()

    because then, we can use a fastpath in pandas.
       )ry   )r&   s    r'   is_simple_aggregationr      s     ;;?r)   c                    t        | d   j                        }| dd  D ]1  }||j                  |j                  |j                         .d } |S  |S )Nr   r/   )r   rQ   rV   )parsed_exprsrX   rZ   s      r'   combine_root_namesr   1  s_    l1o112JAB!*!!#//2!
   r)   c                H    | d   j                   | d   j                   dd S dS )z"Returns the left-most output name.r   Nr/   )rR   )r   s    r'   reduce_output_namesr   =  s9     ?((4 	Q%%bq) r)   N)r$   z'CompliantDataFrame | CompliantLazyFramer%   &IntoCompliantExpr[CompliantSeriesT_co]rw   Sequence[CompliantSeriesT_co])r$   r   r5   r   r6   r   rw   r   )r$   r   r&   z&CompliantExpr[CompliantSeriesT_co] | Trw   z!Sequence[CompliantSeriesT_co] | T)r5   r   r!   'CompliantNamespace[CompliantSeriesT_co]r6   r   rw   z,Sequence[CompliantExpr[CompliantSeriesT_co]])r%   r   r!   r   rw   z"CompliantExpr[CompliantSeriesT_co])r&   rA   rW   r   rw   z)tuple[list[str] | None, list[str] | None])
r&   r   r`   rK   r\   boolrW   r   rw   r   )
r&   r   r`   rK   r\   r   rW   r   rw   r   )
r&   ArrowExprT | PandasLikeExprTr`   rK   r\   r   rW   r   rw   r   )
r&   r   r}   rK   r`   rK   rW   r   rw   r   )
r&   r   r}   rK   r`   rK   rW   r   rw   r   )
r&   r   r}   rK   r`   rK   rW   r   rw   r   )r&   rA   rw   r   )r   zSequence[CompliantExpr[Any]]rw   zlist[str] | None)1
__future__r   r   typingr   r   r   r   r	   r
   r   narwhals.dependenciesr   narwhals.exceptionsr   narwhals.utilsr   typing_extensionsr   narwhals._arrow.exprr   narwhals._pandas_like.exprr   narwhals.typingr   r   r   r   r   r   rK   r   __annotations__r   r   r   r   r   r(   r>   rD   rF   r"   r[   ra   r~   r   r   r   r^   r)   r'   <module>r      s   #          0 4 )+.92-22/3 	)*S03FF y  -]35GHN#uY-F'G /~FOY7JA/5 #2 : #	*"H&26 : 2	B5B 7B (	B8$
$(+$.$@ 

 !	

 	
   
 

 !	

 	
   
 !	A
&A
A 	A
 A "AH 

(+36BE 
 

-08;GJ 

&  	
 "@"	r)   