Skip to content

Commit aa43d13

Browse files
authored
Consider key order in spaces.Dict.__eq__ (#3024)
1 parent 51c2026 commit aa43d13

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

gym/spaces/dict.py

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,12 @@ def __init__(
8181

8282
if spaces is None:
8383
spaces = spaces_kwargs
84-
if isinstance(spaces, dict) and not isinstance(spaces, OrderedDict):
84+
if isinstance(spaces, Mapping) and not isinstance(spaces, OrderedDict):
8585
try:
8686
spaces = OrderedDict(sorted(spaces.items()))
87-
except TypeError: # raise when sort by different types of keys
87+
except TypeError:
88+
# Incomparable types (e.g. `int` vs. `str`, or user-defined types) found.
89+
# The keys remain in the insertion order.
8890
spaces = OrderedDict(spaces.items())
8991
if isinstance(spaces, Sequence):
9092
spaces = OrderedDict(spaces)
@@ -196,7 +198,17 @@ def __len__(self) -> int:
196198

197199
def __repr__(self) -> str:
198200
"""Gives a string representation of this space."""
199-
return "Dict(" + ", ".join([f"{k}: {s}" for k, s in self.spaces.items()]) + ")"
201+
return (
202+
"Dict(" + ", ".join([f"{k!r}: {s}" for k, s in self.spaces.items()]) + ")"
203+
)
204+
205+
def __eq__(self, other) -> bool:
206+
"""Check whether `other` is equivalent to this instance."""
207+
return (
208+
isinstance(other, Dict)
209+
# Comparison of `OrderedDict`s is order-sensitive
210+
and self.spaces == other.spaces # OrderedDict.__eq__
211+
)
200212

201213
def to_jsonable(self, sample_n: list) -> dict:
202214
"""Convert a batch of samples from this space to a JSONable data type."""

0 commit comments

Comments
 (0)