Skip to content

Commit

Permalink
Add back Type hash __slots__ and add test cases. (ros2#1245)
Browse files Browse the repository at this point in the history
* Add types to TypeHash and add test cases

Signed-off-by: Michael Carlstrom <rmc@carlstrom.com>
  • Loading branch information
InvincibleRMC committed Mar 24, 2024
1 parent 49f0103 commit 0f2fdf3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 14 deletions.
25 changes: 11 additions & 14 deletions rclpy/rclpy/type_hash.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,56 +18,53 @@ class TypeHash:

_TYPE_HASH_SIZE = 32

# ros2cli needs __slots__ to avoid API break from https://github.com/ros2/rclpy/pull/1243.
# __slots__ is also used improve performance of Python objects.
__slots__ = [
'_version',
'_value',
]

def __init__(self, **kwargs):
assert all('_' + key in self.__slots__ for key in kwargs.keys()), \
'Invalid arguments passed to constructor: %r' % kwargs.keys()

self.version = kwargs.get('version', -1)
self.value = kwargs.get('value', bytes(self._TYPE_HASH_SIZE))
def __init__(self, version: int = -1, value: bytes = bytes(_TYPE_HASH_SIZE)):
self.version = version
self.value = value

@property
def version(self):
def version(self) -> int:
"""
Get field 'version'.
:returns: version attribute
:rtype: int
"""
return self._version

@version.setter
def version(self, value):
def version(self, value: int) -> None:
assert isinstance(value, int)
self._version = value

@property
def value(self):
def value(self) -> bytes:
"""
Get field 'value'.
:returns: value attribute
:rtype: bytes
"""
return self._value

@value.setter
def value(self, value):
def value(self, value: bytes) -> None:
assert isinstance(value, bytes)
self._value = value

def __eq__(self, other):
def __eq__(self, other: object) -> bool:
if not isinstance(other, TypeHash):
return False
return all(
self.__getattribute__(slot) == other.__getattribute__(slot)
for slot in self.__slots__)

def __str__(self):
def __str__(self) -> str:
if self._version <= 0 or len(self._value) != self._TYPE_HASH_SIZE:
return 'INVALID'

Expand Down
5 changes: 5 additions & 0 deletions rclpy/test/test_type_hash.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class TestTypeHash(unittest.TestCase):

def test_dict_constructor(self):
type_hash = TypeHash(**STD_MSGS_STRING_TYPE_HASH_DICT)
self.assertTrue(hasattr(type_hash, '__slots__'))
self.assertEqual(STD_MSGS_STRING_TYPE_HASH_DICT['version'], type_hash.version)
self.assertEqual(STD_MSGS_STRING_TYPE_HASH_DICT['value'], type_hash.value)

Expand All @@ -42,3 +43,7 @@ def test_print_invalid(self):
actual_str = str(TypeHash())
expected_str = 'INVALID'
self.assertEqual(expected_str, actual_str)

def test_equals(self):
self.assertEqual(TypeHash(), TypeHash())
self.assertNotEqual(TypeHash(version=5), TypeHash())

0 comments on commit 0f2fdf3

Please sign in to comment.