Skip to content

Commit

Permalink
Fix __getattr__ warning (#676)
Browse files Browse the repository at this point in the history
  • Loading branch information
pseudo-rnd-thoughts authored Aug 21, 2023
1 parent 7ddce8c commit 81b87ef
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 5 deletions.
2 changes: 1 addition & 1 deletion gymnasium/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
"error",
"logger",
]
__version__ = "0.29.0"
__version__ = "0.29.1"


# Initializing pygame initializes audio connections through SDL. SDL uses alsa by default on all Linux systems
Expand Down
18 changes: 16 additions & 2 deletions gymnasium/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,20 @@
if TYPE_CHECKING:
from gymnasium.envs.registration import EnvSpec, WrapperSpec


__all__ = [
"Env",
"Wrapper",
"ObservationWrapper",
"RewardWrapper",
"ActionWrapper",
"ObsType",
"ActType",
"RenderFrame",
"WrapperObsType",
"WrapperActType",
]

ObsType = TypeVar("ObsType")
ActType = TypeVar("ActType")
RenderFrame = TypeVar("RenderFrame")
Expand Down Expand Up @@ -296,7 +310,7 @@ def __getattr__(self, name: str) -> Any:
raise AttributeError(f"accessing private attribute '{name}' is prohibited")
logger.warn(
f"env.{name} to get variables from other wrappers is deprecated and will be removed in v1.0, "
f"to get this variable you can do `env.unwrapped.{name}` for environment variables or `env.get_attr('{name}')` that will search the reminding wrappers."
f"to get this variable you can do `env.unwrapped.{name}` for environment variables or `env.get_wrapper_attr('{name}')` that will search the reminding wrappers."
)
return getattr(self.env, name)

Expand All @@ -309,7 +323,7 @@ def get_wrapper_attr(self, name: str) -> Any:
Returns:
The variable with name in wrapper or lower environments
"""
if hasattr(self, name):
if name in self.__dir__(): # todo change in v1.0.0 to `hasattr`
return getattr(self, name)
else:
try:
Expand Down
5 changes: 5 additions & 0 deletions gymnasium/vector/vector_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from numpy.typing import NDArray

import gymnasium as gym
from gymnasium import logger
from gymnasium.vector.utils.spaces import batch_space


Expand Down Expand Up @@ -385,6 +386,10 @@ def set_attr(self, name, values):
def __getattr__(self, name):
if name.startswith("_"):
raise AttributeError(f"attempted to get missing private attribute '{name}'")
logger.warn(
f"env.{name} to get variables from other wrappers is deprecated and will be removed in v1.0, "
f"to get this variable you can do `env.unwrapped.{name}` for environment variables."
)
return getattr(self.env, name)

@property
Expand Down
5 changes: 3 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ accept-rom-license = ["autorom[accept-rom-license] ~=0.4.2"]
box2d = ["box2d-py ==2.3.5", "pygame >=2.1.3", "swig ==4.*"]
classic-control = ["pygame >=2.1.3"]
classic_control = ["pygame >=2.1.3"] # kept for backward compatibility
mujoco-py = ["mujoco-py >=2.1,<2.2"]
mujoco_py = ["mujoco-py >=2.1,<2.2"] # kept for backward compatibility
mujoco-py = ["mujoco-py >=2.1,<2.2", "cython<3"]
mujoco_py = ["mujoco-py >=2.1,<2.2", "cython<3"] # kept for backward compatibility
mujoco = ["mujoco >=2.3.3", "imageio >=2.14.1"]
toy-text = ["pygame >=2.1.3"]
toy_text = ["pygame >=2.1.3"] # kept for backward compatibility
Expand All @@ -65,6 +65,7 @@ all = [
"pygame >=2.1.3",
# mujoco-py
"mujoco-py >=2.1,<2.2",
"cython<3",
# mujoco
"mujoco >=2.3.3",
"imageio >=2.14.1",
Expand Down
21 changes: 21 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
"""Checks that the core Gymnasium API is implemented as expected."""
import re
import warnings
from typing import Any, Dict, Optional, SupportsFloat, Tuple

import numpy as np
import pytest

import gymnasium as gym
from gymnasium import Env, ObservationWrapper, RewardWrapper, Wrapper, spaces
from gymnasium.core import (
ActionWrapper,
Expand Down Expand Up @@ -326,3 +328,22 @@ def test_wrapper_types():
action_env = ExampleActionWrapper(env)
obs, _, _, _, _ = action_env.step(0)
assert obs == np.array([1])


def test_get_wrapper_attr():
env = gym.make("CartPole-v1")

with warnings.catch_warnings(record=True) as caught_warnings:
gravity = env.get_wrapper_attr("gravity")

assert gravity == env.unwrapped.gravity
assert len(caught_warnings) == 0

with pytest.warns(
UserWarning,
match=re.escape(
"env.gravity to get variables from other wrappers is deprecated and will be removed in v1.0, to get this variable you can do `env.unwrapped.gravity` for environment variables or `env.get_wrapper_attr('gravity')` that will search the reminding wrappers."
),
):
gravity = env.gravity
assert gravity == env.unwrapped.gravity

0 comments on commit 81b87ef

Please sign in to comment.