Skip to content

Commit c2caf5e

Browse files
change identifier replacer to allow for all valid Python identifiers (#202)
1 parent f336c67 commit c2caf5e

File tree

2 files changed

+6
-6
lines changed

2 files changed

+6
-6
lines changed

src/latexify/transformers/identifier_replacer.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@
33
from __future__ import annotations
44

55
import ast
6-
import re
6+
import keyword
77
import sys
8-
from typing import ClassVar, cast
8+
from typing import cast
99

1010

1111
class IdentifierReplacer(ast.NodeTransformer):
@@ -24,8 +24,6 @@ def x(y):
2424
return z
2525
"""
2626

27-
_IDENTIFIER_PATTERN: ClassVar[re.Pattern] = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
28-
2927
def __init__(self, mapping: dict[str, str]):
3028
"""Initializer.
3129
@@ -38,9 +36,9 @@ def __init__(self, mapping: dict[str, str]):
3836
self._mapping = mapping
3937

4038
for k, v in self._mapping.items():
41-
if not self._IDENTIFIER_PATTERN.match(k):
39+
if not str.isidentifier(k) or keyword.iskeyword(k):
4240
raise ValueError(f"'{k}' is not an identifier name.")
43-
if not self._IDENTIFIER_PATTERN.match(v):
41+
if not str.isidentifier(v) or keyword.iskeyword(v):
4442
raise ValueError(f"'{v}' is not an identifier name.")
4543

4644
def _replace_args(self, args: list[ast.arg]) -> list[ast.arg]:

src/latexify/transformers/identifier_replacer_test.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ def test_invalid_mapping() -> None:
1515
IdentifierReplacer({"123": "foo"})
1616
with pytest.raises(ValueError, match=r"'456' is not an identifier name."):
1717
IdentifierReplacer({"foo": "456"})
18+
with pytest.raises(ValueError, match=r"'def' is not an identifier name."):
19+
IdentifierReplacer({"foo": "def"})
1820

1921

2022
def test_name_replaced() -> None:

0 commit comments

Comments
 (0)