Skip to content

Commit 80bef7c

Browse files
authored
Improve logic to avoid keyword collisions in generated code
Use the standard library keyword module instead of a hard coded list and applying it to enum keys as well.
1 parent 804805f commit 80bef7c

File tree

2 files changed

+10
-37
lines changed

2 files changed

+10
-37
lines changed

src/betterproto/casing.py

Lines changed: 7 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import keyword
12
import re
23

34
# Word delimiters and symbols that will not be preserved when re-casing.
@@ -16,42 +17,7 @@
1617
def safe_snake_case(value: str) -> str:
1718
"""Snake case a value taking into account Python keywords."""
1819
value = snake_case(value)
19-
if value in [
20-
"and",
21-
"as",
22-
"assert",
23-
"async",
24-
"await",
25-
"break",
26-
"class",
27-
"continue",
28-
"def",
29-
"del",
30-
"elif",
31-
"else",
32-
"except",
33-
"finally",
34-
"for",
35-
"from",
36-
"global",
37-
"if",
38-
"import",
39-
"in",
40-
"is",
41-
"lambda",
42-
"nonlocal",
43-
"not",
44-
"or",
45-
"pass",
46-
"raise",
47-
"return",
48-
"try",
49-
"while",
50-
"with",
51-
"yield",
52-
]:
53-
# https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles
54-
value += "_"
20+
value = sanitize_name(value)
5521
return value
5622

5723

@@ -120,3 +86,8 @@ def camel_case(value: str, strict: bool = True):
12086

12187
def lowercase_first(value: str):
12288
return value[0:1].lower() + value[1:]
89+
90+
91+
def sanitize_name(value: str) -> str:
92+
# https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles
93+
return f"{value}_" if keyword.iskeyword(value) else value

src/betterproto/plugin/models.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,8 @@
5454
pythonize_method_name,
5555
)
5656

57+
from ..casing import sanitize_name
58+
5759
try:
5860
# betterproto[compiler] specific dependencies
5961
from google.protobuf.compiler import plugin_pb2 as plugin
@@ -542,7 +544,7 @@ def __post_init__(self):
542544
# Get entries/allowed values for this Enum
543545
self.entries = [
544546
self.EnumEntry(
545-
name=entry_proto_value.name,
547+
name=sanitize_name(entry_proto_value.name),
546548
value=entry_proto_value.number,
547549
comment=get_comment(
548550
proto_file=self.proto_file, path=self.path + [2, entry_number]

0 commit comments

Comments
 (0)