Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve 'set_wrapper_attr'. #1294

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 19 additions & 19 deletions gymnasium/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,9 +273,12 @@ def get_wrapper_attr(self, name: str) -> Any:
"""Gets the attribute `name` from the environment."""
return getattr(self, name)

def set_wrapper_attr(self, name: str, value: Any):
def set_wrapper_attr(self, name: str, value: Any, *, force: bool = True):
"""Sets the attribute `name` on the environment with `value`."""
setattr(self, name, value)
if force or hasattr(self, name):
setattr(self, name, value)
else:
raise AttributeError(f"{self} has no attribute {name!r}")


WrapperObsType = TypeVar("WrapperObsType")
Expand Down Expand Up @@ -425,30 +428,27 @@ def get_wrapper_attr(self, name: str) -> Any:
f"wrapper {self.class_name()} has no attribute {name!r}"
) from e

def set_wrapper_attr(self, name: str, value: Any):
def set_wrapper_attr(self, name: str, value: Any, *, force: bool = True):
"""Sets an attribute on this wrapper or lower environment if `name` is already defined.

Args:
name: The variable name
value: The new variable value
force: Whether to create the attribute on this wrapper if it does not exists on the
lower environment instead of raising an exception
"""
sub_env = self

# loop through all the wrappers, checking if it has the variable name then setting it
# otherwise stripping the wrapper to check the next.
# end when the core env is reached
while isinstance(sub_env, Wrapper):
if hasattr(sub_env, name):
setattr(sub_env, name, value)
return

sub_env = sub_env.env

# check if the base environment has the wrapper, otherwise, we set it on the top (this) wrapper
if hasattr(sub_env, name):
setattr(sub_env, name, value)
else:
if hasattr(self, name):
setattr(self, name, value)
else:
try:
self.env.set_wrapper_attr(name, value, force=False)
except AttributeError as e:
if force:
setattr(self, name, value)
else:
raise AttributeError(
f"wrapper {self.class_name()} has no attribute {name!r}"
) from e

def __str__(self):
"""Returns the wrapper name and the :attr:`env` representation string."""
Expand Down
Loading