From 44edf9c68580fde9a8ce316b9614e4b11466e79b Mon Sep 17 00:00:00 2001 From: 1AbdullahButt <168034895+1AbdullahButt@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:02:26 +0500 Subject: [PATCH] Include string_type in StringArray equality StringArray inherited Array.__eq__, which only compares shape and dtype. Every StringArray has dtype object, so a str spec and a bytes spec compared equal even though they accept different values. Compare string_type too, the same way BoundedArray extends equality with its bounds. Fixes #26. --- dm_env/specs.py | 6 ++++++ dm_env/specs_test.py | 25 +++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/dm_env/specs.py b/dm_env/specs.py index 0dc989a..19e064a 100644 --- a/dm_env/specs.py +++ b/dm_env/specs.py @@ -400,5 +400,11 @@ def generate_value(self): def __repr__(self): return self._REPR_TEMPLATE.format(self=self) # pytype: disable=duplicate-keyword-argument + def __eq__(self, other): + if not isinstance(other, StringArray): + return False + return (super(StringArray, self).__eq__(other) and + self.string_type == other.string_type) + def __reduce__(self): return type(self), (self.shape, self.string_type, self.name) diff --git a/dm_env/specs_test.py b/dm_env/specs_test.py index 63a243e..3a42cac 100644 --- a/dm_env/specs_test.py +++ b/dm_env/specs_test.py @@ -486,5 +486,30 @@ def testSerialization(self, shape, string_type, name): spec = specs.StringArray(shape=shape, string_type=string_type, name=name) self.assertEqual(pickle.loads(pickle.dumps(spec)), spec) + @parameterized.parameters( + dict(shape=()), dict(shape=(2,)), dict(shape=(2, 3))) + def testEqual(self, shape): + spec_1 = specs.StringArray(shape=shape, string_type=bytes, name="foo") + spec_2 = specs.StringArray(shape=shape, string_type=bytes, name="bar") + self.assertEqual(spec_1, spec_2) + + @parameterized.parameters( + dict(shape=()), dict(shape=(2,)), dict(shape=(2, 3))) + def testNotEqualDifferentStringType(self, shape): + spec_1 = specs.StringArray(shape=shape, string_type=str) + spec_2 = spec_1.replace(string_type=bytes) + self.assertNotEqual(spec_1, spec_2) + self.assertNotEqual(spec_2, spec_1) + + def testNotEqualDifferentShape(self): + spec_1 = specs.StringArray(shape=(2,), string_type=str) + spec_2 = specs.StringArray(shape=(3,), string_type=str) + self.assertNotEqual(spec_1, spec_2) + + def testIsUnhashable(self): + spec = specs.StringArray(shape=(2,)) + with self.assertRaisesRegex(TypeError, "unhashable type"): + hash(spec) + if __name__ == "__main__": absltest.main()