Skip to content

Commit

Permalink
Fix for issue pandas-dev#28283: Ensure DataFrame.eval calls __finalize__
Browse files Browse the repository at this point in the history
  • Loading branch information
root committed May 15, 2024
1 parent 283a2dc commit 2895b9b
Showing 1 changed file with 26 additions and 17 deletions.
43 changes: 26 additions & 17 deletions pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -4628,27 +4628,36 @@ def query(self, expr: str, *, inplace: bool = False, **kwargs) -> DataFrame | No
return result

@overload
def eval(self, expr: str, *, inplace: Literal[False] = ..., **kwargs) -> Any: ...

@overload
def eval(self, expr: str, *, inplace: Literal[True], **kwargs) -> None: ...
def eval(self, expr: str, *, inplace: bool = False, **kwargs) -> Any | None:
"""
Evaluate a string describing operations on DataFrame columns.
def eval(self, expr: str, *, inplace: bool = False, **kwargs) -> Any | None:
"""
Evaluate a string describing operations on DataFrame columns.
Operates on columns only, not specific rows or elements. This allows
`eval` to run arbitrary code, which can make you vulnerable to code
injection if you pass user input to this function.
Operates on columns only, not specific rows or elements. This allows
`eval` to run arbitrary code, which can make you vulnerable to code
injection if you pass user input to this function.
Parameters
----------
expr : str
The expression string to evaluate.
inplace : bool, default False
If the expression contains an assignment, whether to perform the
operation inplace and mutate the existing DataFrame. Otherwise,
a new DataFrame is returned.
"""
from pandas.core.computation.eval import eval as _eval

if not isinstance(expr, str):
msg = f"expr must be a string to be evaluated, {type(expr)} given"
raise ValueError(msg)

# Ensure __finalize__ is called to propagate metadata
result = super().eval(expr, inplace=inplace, **kwargs)
if not inplace:
result = result.__finalize__(self, method="eval")
return result

Parameters
----------
expr : str
The expression string to evaluate.
inplace : bool, default False
If the expression contains an assignment, whether to perform the
operation inplace and mutate the existing DataFrame. Otherwise,
a new DataFrame is returned.
**kwargs
See the documentation for :func:`eval` for complete details
on the keyword arguments accepted by
Expand Down

0 comments on commit 2895b9b

Please sign in to comment.