Skip to content

Commit

Permalink
Improve logic to avoid keyword collisions in generated code
Browse files Browse the repository at this point in the history
Use the standard library keyword module instead of a hard coded list and applying it to enum keys as well.
  • Loading branch information
Gobot1234 committed Aug 9, 2020
1 parent 804805f commit 80bef7c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 37 deletions.
43 changes: 7 additions & 36 deletions src/betterproto/casing.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import keyword
import re

# Word delimiters and symbols that will not be preserved when re-casing.
Expand All @@ -16,42 +17,7 @@
def safe_snake_case(value: str) -> str:
"""Snake case a value taking into account Python keywords."""
value = snake_case(value)
if value in [
"and",
"as",
"assert",
"async",
"await",
"break",
"class",
"continue",
"def",
"del",
"elif",
"else",
"except",
"finally",
"for",
"from",
"global",
"if",
"import",
"in",
"is",
"lambda",
"nonlocal",
"not",
"or",
"pass",
"raise",
"return",
"try",
"while",
"with",
"yield",
]:
# https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles
value += "_"
value = sanitize_name(value)
return value


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

def lowercase_first(value: str):
return value[0:1].lower() + value[1:]


def sanitize_name(value: str) -> str:
# https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles
return f"{value}_" if keyword.iskeyword(value) else value
4 changes: 3 additions & 1 deletion src/betterproto/plugin/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@
pythonize_method_name,
)

from ..casing import sanitize_name

try:
# betterproto[compiler] specific dependencies
from google.protobuf.compiler import plugin_pb2 as plugin
Expand Down Expand Up @@ -542,7 +544,7 @@ def __post_init__(self):
# Get entries/allowed values for this Enum
self.entries = [
self.EnumEntry(
name=entry_proto_value.name,
name=sanitize_name(entry_proto_value.name),
value=entry_proto_value.number,
comment=get_comment(
proto_file=self.proto_file, path=self.path + [2, entry_number]
Expand Down

0 comments on commit 80bef7c

Please sign in to comment.