Skip to content

Commit

Permalink
change identifier replacer to allow for all valid Python identifiers (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
marvinvanaalst authored Dec 8, 2023
1 parent f336c67 commit c2caf5e
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 6 deletions.
10 changes: 4 additions & 6 deletions src/latexify/transformers/identifier_replacer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
from __future__ import annotations

import ast
import re
import keyword
import sys
from typing import ClassVar, cast
from typing import cast


class IdentifierReplacer(ast.NodeTransformer):
Expand All @@ -24,8 +24,6 @@ def x(y):
return z
"""

_IDENTIFIER_PATTERN: ClassVar[re.Pattern] = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")

def __init__(self, mapping: dict[str, str]):
"""Initializer.
Expand All @@ -38,9 +36,9 @@ def __init__(self, mapping: dict[str, str]):
self._mapping = mapping

for k, v in self._mapping.items():
if not self._IDENTIFIER_PATTERN.match(k):
if not str.isidentifier(k) or keyword.iskeyword(k):
raise ValueError(f"'{k}' is not an identifier name.")
if not self._IDENTIFIER_PATTERN.match(v):
if not str.isidentifier(v) or keyword.iskeyword(v):
raise ValueError(f"'{v}' is not an identifier name.")

def _replace_args(self, args: list[ast.arg]) -> list[ast.arg]:
Expand Down
2 changes: 2 additions & 0 deletions src/latexify/transformers/identifier_replacer_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ def test_invalid_mapping() -> None:
IdentifierReplacer({"123": "foo"})
with pytest.raises(ValueError, match=r"'456' is not an identifier name."):
IdentifierReplacer({"foo": "456"})
with pytest.raises(ValueError, match=r"'def' is not an identifier name."):
IdentifierReplacer({"foo": "def"})


def test_name_replaced() -> None:
Expand Down

0 comments on commit c2caf5e

Please sign in to comment.