Skip to content

Commit f9efe9d

Browse files
escape backticks properly
1 parent 004c589 commit f9efe9d

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

pandas/core/computation/parsing.py

+8
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ def create_valid_python_identifier(name: str) -> str:
5959
"'": "_SINGLEQUOTE_",
6060
'"': "_DOUBLEQUOTE_",
6161
"#": "_HASH_",
62+
"`": "_BACKTICK_",
6263
}
6364
)
6465

@@ -213,6 +214,13 @@ def _split_by_backtick(s: str) -> list[tuple[bool, str]]:
213214
# Backtick opened before quote
214215
if (quote_index == -1) or (backtick_index < quote_index):
215216
next_backtick_index = s.find("`", backtick_index + 1)
217+
while (
218+
(next_backtick_index != -1)
219+
and (next_backtick_index != len(s) - 1)
220+
and (s[next_backtick_index + 1] == "`")
221+
):
222+
# Since the next character is also a backtick, it's an escaped backtick
223+
next_backtick_index = s.find("`", next_backtick_index + 2)
216224

217225
# Backtick is unmatched (Bad syntax)
218226
if next_backtick_index == -1:

pandas/tests/computation/test_eval.py

+9
Original file line numberDiff line numberDiff line change
@@ -2002,6 +2002,15 @@ def test_query_on_expr_with_column_name_with_backtick_and_hash():
20022002
tm.assert_frame_equal(result, expected)
20032003

20042004

2005+
def test_query_on_expr_with_column_name_with_backtick():
2006+
# GH 59285
2007+
df = DataFrame({"a`b": (1, 2, 3), "ab": (4, 5, 6)})
2008+
result = df.query("`a``b` < 2")
2009+
# Note: Formatting checks may wrongly consider the above``inline code``.
2010+
expected = df[df["a`b"] < 2]
2011+
tm.assert_frame_equal(result, expected)
2012+
2013+
20052014
def test_query_on_expr_with_string_with_backticks():
20062015
# GH 59285
20072016
df = DataFrame(("`", "`````", "``````````"), columns=["#backticks"])

0 commit comments

Comments
 (0)