Skip to content

Commit

Permalink
Override protobuf Message.__dir__ method
Browse files Browse the repository at this point in the history
Add a new implementation of Message.__dir__ method that filters out
attributes which are not accessible. Such an attribute is currently
only `Extensions`, which is only accessible if any extension exists.
Add a unit test that verifies all remaining attributes can be accessed.

PiperOrigin-RevId: 700778715
  • Loading branch information
AleksMat authored and copybara-github committed Nov 27, 2024
1 parent 602b62a commit 9668016
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
21 changes: 21 additions & 0 deletions python/google/protobuf/internal/message_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1268,6 +1268,27 @@ def testReturningType(self, message_module):
self.assertEqual(bool, type(m.repeated_bool[0]))
self.assertEqual(True, m.repeated_bool[0])

def testDir(self, message_module):
m = message_module.TestAllTypes()
attributes = dir(m)
self.assertGreaterEqual(len(attributes), 55)
self.assertIn('DESCRIPTOR', attributes)

class_attributes = dir(type(m))
attribute_set = set(attributes)
for attr in class_attributes:
if attr != 'Extensions':
self.assertIn(attr, attribute_set)

def testAllAttributeFromDirAccessible(self, message_module):
m = message_module.TestAllTypes()
attributes = dir(m)
for attribute in attributes:
try:
getattr(m, attribute)
except AttributeError:
self.fail(f'Attribute {attribute} is not accessible.')

def testEquality(self, message_module):
m = message_module.TestAllTypes()
m2 = message_module.TestAllTypes()
Expand Down
17 changes: 17 additions & 0 deletions python/google/protobuf/message.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@

__author__ = '[email protected] (Will Robinson)'

_INCONSISTENT_MESSAGE_ATTRIBUTES = ('Extensions',)


class Error(Exception):
"""Base error type for this module."""
pass
Expand Down Expand Up @@ -56,6 +59,20 @@ def __deepcopy__(self, memo=None):
clone.MergeFrom(self)
return clone

def __dir__(self):
"""Filters out attributes that would raise AttributeError if accessed."""
missing_attributes = set()
for attribute in _INCONSISTENT_MESSAGE_ATTRIBUTES:
try:
getattr(self, attribute)
except AttributeError:
missing_attributes.add(attribute)
return [
attribute
for attribute in super().__dir__()
if attribute not in missing_attributes
]

def __eq__(self, other_msg):
"""Recursively compares two messages by value and structure."""
raise NotImplementedError
Expand Down

0 comments on commit 9668016

Please sign in to comment.