Skip to content

Disallow .__call__() as workaround for non-named functions #32460

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
May 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions doc/source/whatsnew/v1.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -784,6 +784,7 @@ Reshaping
- Bug in :func:`concat` was not allowing for concatenation of ``DataFrame`` and ``Series`` with duplicate keys (:issue:`33654`)
- Bug in :func:`cut` raised an error when non-unique labels (:issue:`33141`)
- Bug in :meth:`DataFrame.replace` casts columns to ``object`` dtype if items in ``to_replace`` not in values (:issue:`32988`)
- Ensure only named functions can be used in :func:`eval()` (:issue:`32460`)


Sparse
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/computation/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -641,7 +641,7 @@ def visit_Attribute(self, node, **kwargs):

def visit_Call(self, node, side=None, **kwargs):

if isinstance(node.func, ast.Attribute):
if isinstance(node.func, ast.Attribute) and node.func.attr != "__call__":
res = self.visit_Attribute(node.func)
elif not isinstance(node.func, ast.Name):
raise TypeError("Only named functions are supported")
Expand Down
21 changes: 21 additions & 0 deletions pandas/tests/frame/test_query_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -1181,3 +1181,24 @@ def test_failing_character_outside_range(self, df):
def test_failing_hashtag(self, df):
with pytest.raises(SyntaxError):
df.query("`foo#bar` > 4")

def test_call_non_named_expression(self, df):
"""
Only attributes and variables ('named functions') can be called.
.__call__() is not an allowed attribute because that would allow
calling anything.
https://github.com/pandas-dev/pandas/pull/32460
"""

def func(*_):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add the issue number here as a comment.

return 1

funcs = [func] # noqa

df.eval("@func()")

with pytest.raises(TypeError, match="Only named functions are supported"):
df.eval("@funcs[0]()")

with pytest.raises(TypeError, match="Only named functions are supported"):
df.eval("@funcs[0].__call__()")