Skip to content

Commit

Permalink
Consider key order in spaces.Dict.__eq__ (#3024)
Browse files Browse the repository at this point in the history
  • Loading branch information
XuehaiPan authored Aug 18, 2022
1 parent 51c2026 commit aa43d13
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions gym/spaces/dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,12 @@ def __init__(

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

def __repr__(self) -> str:
"""Gives a string representation of this space."""
return "Dict(" + ", ".join([f"{k}: {s}" for k, s in self.spaces.items()]) + ")"
return (
"Dict(" + ", ".join([f"{k!r}: {s}" for k, s in self.spaces.items()]) + ")"
)

def __eq__(self, other) -> bool:
"""Check whether `other` is equivalent to this instance."""
return (
isinstance(other, Dict)
# Comparison of `OrderedDict`s is order-sensitive
and self.spaces == other.spaces # OrderedDict.__eq__
)

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

0 comments on commit aa43d13

Please sign in to comment.