Skip to content

Commit 13221e0

Browse files
committed
pycodegen: safe identifiers don't have periods nor start with digits
1 parent 8c39683 commit 13221e0

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

schema_salad/python_codegen.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -97,10 +97,12 @@ def safe_name(name: str) -> str:
9797
avn = schema.avro_field_name(name)
9898
if avn.startswith("anon."):
9999
avn = avn[5:]
100-
if avn in ("class", "in"):
100+
elif avn[0].isdigit():
101+
avn = f"_{avn}"
102+
elif avn in ("class", "in"):
101103
# reserved words
102-
avn = avn + "_"
103-
return avn
104+
avn = f"{avn}_"
105+
return avn.replace(".", "_")
104106

105107
def prologue(self) -> None:
106108
"""Trigger to generate the prolouge code."""

schema_salad/tests/test_python_codegen.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,18 @@
1212
from schema_salad import codegen
1313
from schema_salad.avro.schema import Names
1414
from schema_salad.fetcher import DefaultFetcher
15+
from schema_salad.python_codegen import PythonCodeGen
1516
from schema_salad.python_codegen_support import LoadingOptions
1617
from schema_salad.schema import load_schema
1718

1819
from .util import basket_file_uri, cwl_file_uri, get_data, metaschema_file_uri
1920

2021

22+
def test_safe_identifiers() -> None:
23+
"""Affirm correct construction of identifiers safe for Python."""
24+
assert PythonCodeGen.safe_name("5.8s_pattern") == "_5_8s_pattern"
25+
26+
2127
def test_cwl_gen(tmp_path: Path) -> None:
2228
src_target = tmp_path / "src.py"
2329
python_codegen(cwl_file_uri, src_target)

0 commit comments

Comments
 (0)