Skip to content

Commit

Permalink
Add has_wrapper_attr
Browse files Browse the repository at this point in the history
  • Loading branch information
pseudo-rnd-thoughts committed May 28, 2024
1 parent 6c315e9 commit faab33d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
11 changes: 11 additions & 0 deletions gymnasium/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,10 @@ def __exit__(self, *args: Any):
# propagate exception
return False

def has_wrapper_attr(self, name: str) -> bool:
"""Checks if the attribute `name` exists in the environment."""
return hasattr(self, name)

def get_wrapper_attr(self, name: str) -> Any:
"""Gets the attribute `name` from the environment."""
return getattr(self, name)
Expand Down Expand Up @@ -392,6 +396,13 @@ def wrapper_spec(cls, **kwargs: Any) -> WrapperSpec:
kwargs=kwargs,
)

def has_wrapper_attr(self, name: str) -> bool:
"""Checks if the given attribute is within the wrapper or its environment."""
if hasattr(self, name):
return True
else:
return self.env.has_wrapper_attr(name)

def get_wrapper_attr(self, name: str) -> Any:
"""Gets an attribute from the wrapper and lower environments if `name` doesn't exist in this object.
Expand Down
14 changes: 5 additions & 9 deletions gymnasium/utils/play.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,13 @@ def _get_relevant_keys(
self, keys_to_action: dict[tuple[int], int] | None = None
) -> set:
if keys_to_action is None:
if hasattr(self.env, "get_keys_to_action"):
keys_to_action = self.env.get_keys_to_action()
elif hasattr(self.env.unwrapped, "get_keys_to_action"):
keys_to_action = self.env.unwrapped.get_keys_to_action()
if self.env.has_wrapper_attr("get_keys_to_action"):
keys_to_action = self.env.get_wrapper_attr("get_keys_to_actions")()
else:
assert self.env.spec is not None
raise MissingKeysToAction(
f"{self.env.spec.id} does not have explicit key to action mapping, "
"please specify one manually"
"please specify one manually, `play(env, keys_to_action=...)`"
)
assert isinstance(keys_to_action, dict)
relevant_keys = set(sum((list(k) for k in keys_to_action.keys()), []))
Expand Down Expand Up @@ -244,10 +242,8 @@ def play(
env.reset(seed=seed)

if keys_to_action is None:
if hasattr(env, "get_keys_to_action"):
keys_to_action = env.get_keys_to_action()
elif hasattr(env.unwrapped, "get_keys_to_action"):
keys_to_action = env.unwrapped.get_keys_to_action()
if env.has_wrapper_attr("get_keys_to_action"):
keys_to_action = env.get_wrapper_attr("get_keys_to_action")()
else:
assert env.spec is not None
raise MissingKeysToAction(
Expand Down

0 comments on commit faab33d

Please sign in to comment.