Skip to content

Commit

Permalink
Disambiguate fields whose names are reserved python words (#514)
Browse files Browse the repository at this point in the history
  • Loading branch information
software-dov authored Jul 10, 2020
1 parent ca59683 commit 3c210a9
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
3 changes: 2 additions & 1 deletion gapic/schema/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -621,7 +621,7 @@ def _get_fields(self,
field_pb.oneof_index
) if is_oneof else None

answer[field_pb.name] = wrappers.Field(
field = wrappers.Field(
field_pb=field_pb,
enum=self.api_enums.get(field_pb.type_name.lstrip('.')),
message=self.api_messages.get(field_pb.type_name.lstrip('.')),
Expand All @@ -631,6 +631,7 @@ def _get_fields(self,
),
oneof=oneof_name,
)
answer[field.name] = field

# Done; return the answer.
return answer
Expand Down
6 changes: 6 additions & 0 deletions gapic/schema/wrappers.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ class Field:
def __getattr__(self, name):
return getattr(self.field_pb, name)

@property
def name(self) -> str:
"""Used to prevent collisions with python keywords"""
name = self.field_pb.name
return name + "_" if name in utils.RESERVED_NAMES else name

@utils.cached_property
def ident(self) -> metadata.FieldIdentifier:
"""Return the identifier to be used in templates."""
Expand Down
12 changes: 12 additions & 0 deletions tests/unit/schema/wrappers/test_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,3 +248,15 @@ def test_mock_value_message():
message=message,
)
assert field.mock_value == 'bogus.Message(foo=324)'


def test_field_name_kword_disambiguation():
from_field = make_field(
name="from",
)
assert from_field.name == "from_"

frum_field = make_field(
name="frum",
)
assert frum_field.name == "frum"

0 comments on commit 3c210a9

Please sign in to comment.