
    Mh6                       S r SSKJr  SSKrSSKJr  SSKrSSKJr  SSK	J
r
  SSKJr  SSKJr  SS	KJrJr  SS
KJr  SSKJr  SSKJr  SSKJr  \(       a  SSKJr  SS jrSS jrS rS rSS jr SS jr!        S         SS jjr"g)z
Top level ``eval`` module.
    )annotationsN)TYPE_CHECKING)find_stack_level)validate_bool_kwargis_extension_array_dtype)ENGINES)PARSERSExpr)tokenize_string)ensure_scope)NDFrame)pprint_thing)BinOpc                    SSK Jn  SSKJn  U c  U(       a  SOSn U [        ;  a/  [        [        R                  " 5       5      n[        SU  SU 35      eU S:X  a  U(       d  [        S5      eU $ )	z
Make sure a valid engine is passed.

Parameters
----------
engine : str
    String to validate.

Raises
------
KeyError
  * If an invalid engine is passed.
ImportError
  * If numexpr was requested but doesn't exist.

Returns
-------
str
    Engine name.
r   )NUMEXPR_INSTALLED)USE_NUMEXPRnumexprpythonzInvalid engine 'z' passed, valid engines are z~'numexpr' is not installed or an unsupported version. Cannot use engine='numexpr' for query/eval if 'numexpr' is not installed)	pandas.core.computation.checkr   #pandas.core.computation.expressionsr   r	   listkeysKeyErrorImportError)enginer   r   valid_enginess       N/var/www/html/env/lib/python3.13/site-packages/pandas/core/computation/eval.py_check_enginer      sv    * @?~)xWW\\^,vh&B=/R
 	
 #4L
 	

 M    c                `    U [         ;  a$  [        SU  S[         R                  " 5        35      eg)z
Make sure a valid parser is passed.

Parameters
----------
parser : str

Raises
------
KeyError
  * If an invalid parser is passed
zInvalid parser 'z' passed, valid parsers are N)r
   r   r   )parsers    r   _check_parserr#   K   s6     Wvh&B7<<>BRS
 	
 r    c                    U b?  U  H8  n[        US5      (       a  M  [        U5      R                  n[        SU S35      e   g g )N__getitem__zResolver of type 'z+' does not implement the __getitem__ method)hasattrtype__name__	TypeError)	resolversresolvernames      r   _check_resolversr-   ^   sQ    !H8]33H~..( /7 7  " r    c                (    U (       d  [        S5      eg)z
Make sure an expression is not an empty string

Parameters
----------
expr : object
    An object that can be converted to a string

Raises
------
ValueError
  * If expr is an empty string
zexpr cannot be an empty stringN)
ValueError)exprs    r   _check_expressionr1   i   s     9:: r    c                2    [        U 5      n[        U5        U$ )a  
Convert an object to an expression.

This function converts an object to an expression (a unicode string) and
checks to make sure it isn't empty after conversion. This is used to
convert operators to their string representation for recursive calls to
:func:`~pandas.eval`.

Parameters
----------
expr : object
    The object to be converted to a string.

Returns
-------
str
    The string representation of an object.

Raises
------
ValueError
  * If the expression is empty.
)r   r1   )r0   ss     r   _convert_expressionr4   {   s    0 	TAaHr    c                    US:H  nUS:g  nU(       a  SnO	U(       a  SnU(       d  U(       a<  [        U 5       H,  u  pgU[        R                  :X  d  M  US:X  d  M#  [        W5      e   g g )Nr   pandasz5The '@' prefix is only supported by the pandas parserzuThe '@' prefix is not allowed in top-level eval calls.
please refer to your variables by name without the '@' prefix.@)r   tokenizeOPSyntaxError)r0   stack_levelr"   at_top_of_stacknot_pandas_parsermsgtoknumtokvals           r   _check_for_localsrA      sh    !Q&O(*E	M 	
 +-d3NF$3!#&& 4 ,r    c	           	     4   [        US5      n[        U [        5      (       aO  [        U 5        U R	                  5        V	s/ s H(  oR                  5       S:w  d  M  U	R                  5       PM*     n
n	OU /n
[        U
5      S:  nU(       a  Uc  [        S5      e[        U5      n[        U5        [        U5        SnSnSnU
 GH  n [        U 5      n [        XU5        [        US-   UUUUS9n[        XXS	9nUS
:X  a  [        UR                   R"                  5      (       dC  [%        UR                   SS5      bO  ['        S UR                   R(                   5       5      (       a$  [*        R,                  " S[.        [1        5       S9  Sn[2        U   nU" U5      nUR5                  5       nUR6                  c$  U(       a  [        S5      eU(       a  [        S5      eUR6                  nUR8                  c  GM4  Uc  GM:  SnU(       dJ  U(       aC   UR8                  n[        U[:        5      (       a  UR=                  SS9nOUR=                  5       nOUR8                  n U(       a(  [        U[:        5      (       a  XR@                  SS2U4'   OXU'    U(       d  UU04nOU H  nUU;   d  M  UUU'     O
   UUU04-  nSnSnGM      USL a  U(       a  U$ U$ gs  sn	f ! [>         a  n[        S5      UeSnAff = f! [B        [D        4 a  n[        S5      UeSnAff = f)a  
Evaluate a Python expression as a string using various backends.

The following arithmetic operations are supported: ``+``, ``-``, ``*``,
``/``, ``**``, ``%``, ``//`` (python engine only) along with the following
boolean operations: ``|`` (or), ``&`` (and), and ``~`` (not).
Additionally, the ``'pandas'`` parser allows the use of :keyword:`and`,
:keyword:`or`, and :keyword:`not` with the same semantics as the
corresponding bitwise operators.  :class:`~pandas.Series` and
:class:`~pandas.DataFrame` objects are supported and behave as they would
with plain ol' Python evaluation.

Parameters
----------
expr : str
    The expression to evaluate. This string cannot contain any Python
    `statements
    <https://docs.python.org/3/reference/simple_stmts.html#simple-statements>`__,
    only Python `expressions
    <https://docs.python.org/3/reference/simple_stmts.html#expression-statements>`__.
parser : {'pandas', 'python'}, default 'pandas'
    The parser to use to construct the syntax tree from the expression. The
    default of ``'pandas'`` parses code slightly different than standard
    Python. Alternatively, you can parse an expression using the
    ``'python'`` parser to retain strict Python semantics.  See the
    :ref:`enhancing performance <enhancingperf.eval>` documentation for
    more details.
engine : {'python', 'numexpr'}, default 'numexpr'

    The engine used to evaluate the expression. Supported engines are

    - None : tries to use ``numexpr``, falls back to ``python``
    - ``'numexpr'`` : This default engine evaluates pandas objects using
      numexpr for large speed ups in complex expressions with large frames.
    - ``'python'`` : Performs operations as if you had ``eval``'d in top
      level python. This engine is generally not that useful.

    More backends may be available in the future.
local_dict : dict or None, optional
    A dictionary of local variables, taken from locals() by default.
global_dict : dict or None, optional
    A dictionary of global variables, taken from globals() by default.
resolvers : list of dict-like or None, optional
    A list of objects implementing the ``__getitem__`` special method that
    you can use to inject an additional collection of namespaces to use for
    variable lookup. For example, this is used in the
    :meth:`~DataFrame.query` method to inject the
    ``DataFrame.index`` and ``DataFrame.columns``
    variables that refer to their respective :class:`~pandas.DataFrame`
    instance attributes.
level : int, optional
    The number of prior stack frames to traverse and add to the current
    scope. Most users will **not** need to change this parameter.
target : object, optional, default None
    This is the target object for assignment. It is used when there is
    variable assignment in the expression. If so, then `target` must
    support item assignment with string keys, and if a copy is being
    returned, it must also support `.copy()`.
inplace : bool, default False
    If `target` is provided, and the expression mutates `target`, whether
    to modify `target` inplace. Otherwise, return a copy of `target` with
    the mutation.

Returns
-------
ndarray, numeric scalar, DataFrame, Series, or None
    The completion value of evaluating the given code or None if ``inplace=True``.

Raises
------
ValueError
    There are many instances where such an error can be raised:

    - `target=None`, but the expression is multiline.
    - The expression is multiline, but not all them have item assignment.
      An example of such an arrangement is this:

      a = b + 1
      a + 2

      Here, there are expressions on different lines, making it multiline,
      but the last line has no variable assigned to the output of `a + 2`.
    - `inplace=True`, but the expression is missing item assignment.
    - Item assignment is provided, but the `target` does not support
      string item assignment.
    - Item assignment is provided and `inplace=False`, but the `target`
      does not support the `.copy()` method

See Also
--------
DataFrame.query : Evaluates a boolean expression to query the columns
        of a frame.
DataFrame.eval : Evaluate a string describing operations on
        DataFrame columns.

Notes
-----
The ``dtype`` of any objects involved in an arithmetic ``%`` operation are
recursively cast to ``float64``.

See the :ref:`enhancing performance <enhancingperf.eval>` documentation for
more details.

Examples
--------
>>> df = pd.DataFrame({"animal": ["dog", "pig"], "age": [10, 20]})
>>> df
  animal  age
0    dog   10
1    pig   20

We can add a new column using ``pd.eval``:

>>> pd.eval("double_age = df.age * 2", target=df)
  animal  age  double_age
0    dog   10          20
1    pig   20          40
inplace    NzPmulti-line expressions are only valid in the context of data, use DataFrame.evalTF)global_dict
local_dictr*   target)r   r"   envr   operand_typesc              3  8   #    U  H  n[        U5      v   M     g 7f)Nr   ).0elems     r   	<genexpr>eval.<locals>.<genexpr>U  s      ;D )..;s   zEngine has switched to 'python' because numexpr does not support extension array dtypes. Please set your engine to python manually.)
stacklevelr   zNMulti-line expressions are only valid if all expressions contain an assignmentz0Cannot operate inplace if there is no assignment)deepz"Cannot return a copy of the targetz)Cannot assign expression output to target)#r   
isinstancestrr1   
splitlinesstriplenr/   r   r#   r-   r4   rA   r   r   r   termsreturn_typegetattranyrJ   warningswarnRuntimeWarningr   r	   evaluateassignerrH   r   copyAttributeErrorlocr)   
IndexError)r0   r"   r   rG   rF   r*   levelrH   rC   eexprs
multi_lineret
first_exprtarget_modifiedrI   parsed_exprengeng_instr_   errr+   s                         r   evalro      s'   B "'95G $$$(OO$5I$5qb$5I UaJfn2
 	
 6"F&Y
CJO"4($v. AI#!
 4vGY$[%6%6%B%BCC{((/4@L '--;;  
 MMU+-	 F fo{#!' ?   !STT ''::!h&:"O zT ZZF!&'22!'$!7!' Wz&'::.1JJq({+'*8$ &_.	 !*H8+-0* !*
 8S/!33ICJq v %(v1c1 ] JZ & T$%IJPSST z* W !LMSVVWsG   KK0K<K.K6	K6
K3"K..K36LLL)r   
str | NonereturnrS   )r"   rS   )rq   rS   )r0   rS   r;   intr"   rS   )r6   NNN r   NF)
r0   zstr | BinOpr"   rS   r   rp   rd   rr   rC   bool)#__doc__
__future__r   r8   typingr   r[   pandas.util._exceptionsr   pandas.util._validatorsr   pandas.core.dtypes.commonr   pandas.core.computation.enginesr	   pandas.core.computation.exprr
   r   pandas.core.computation.parsingr   pandas.core.computation.scoper   pandas.core.genericr   pandas.io.formats.printingr   pandas.core.computation.opsr   r   r#   r-   r1   r4   rA   ro   rs   r    r   <module>r      s    #     4 7 > 3 < 6 ' 31*Z
&;$:'( u2
u2u2 u2 u2 u2r    