Fix exception causes all over the codebase (#205)

This commit is contained in:
Ram Rachum
2022-12-10 16:47:18 +02:00
committed by GitHub
parent a10bcd858e
commit 3d47702984
27 changed files with 72 additions and 70 deletions

View File

@@ -21,10 +21,10 @@ try:
polygonShape, polygonShape,
revoluteJointDef, revoluteJointDef,
) )
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"box2D is not installed, run `pip install gymnasium[box2d]`" "box2D is not installed, run `pip install gymnasium[box2d]`"
) ) from e
if TYPE_CHECKING: if TYPE_CHECKING:
@@ -621,10 +621,10 @@ class BipedalWalker(gym.Env, EzPickle):
try: try:
import pygame import pygame
from pygame import gfxdraw from pygame import gfxdraw
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[box2d]`" "pygame is not installed, run `pip install gymnasium[box2d]`"
) ) from e
if self.screen is None and self.render_mode == "human": if self.screen is None and self.render_mode == "human":
pygame.init() pygame.init()

View File

@@ -17,10 +17,10 @@ from gymnasium.error import DependencyNotInstalled
try: try:
from Box2D.b2 import fixtureDef, polygonShape, revoluteJointDef from Box2D.b2 import fixtureDef, polygonShape, revoluteJointDef
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"box2D is not installed, run `pip install gymnasium[box2d]`" "box2D is not installed, run `pip install gymnasium[box2d]`"
) ) from e
SIZE = 0.02 SIZE = 0.02

View File

@@ -15,20 +15,20 @@ from gymnasium.utils import EzPickle
try: try:
import Box2D import Box2D
from Box2D.b2 import contactListener, fixtureDef, polygonShape from Box2D.b2 import contactListener, fixtureDef, polygonShape
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"box2D is not installed, run `pip install gymnasium[box2d]`" "box2D is not installed, run `pip install gymnasium[box2d]`"
) ) from e
try: try:
# As pygame is necessary for using the environment (reset and step) even without a render mode # As pygame is necessary for using the environment (reset and step) even without a render mode
# therefore, pygame is a necessary import for the environment. # therefore, pygame is a necessary import for the environment.
import pygame import pygame
from pygame import gfxdraw from pygame import gfxdraw
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[box2d]`" "pygame is not installed, run `pip install gymnasium[box2d]`"
) ) from e
STATE_W = 96 # less than Atari 160x192 STATE_W = 96 # less than Atari 160x192

View File

@@ -23,10 +23,10 @@ try:
polygonShape, polygonShape,
revoluteJointDef, revoluteJointDef,
) )
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"box2d is not installed, run `pip install gymnasium[box2d]`" "box2d is not installed, run `pip install gymnasium[box2d]`"
) ) from e
if TYPE_CHECKING: if TYPE_CHECKING:
@@ -618,10 +618,10 @@ class LunarLander(gym.Env, EzPickle):
try: try:
import pygame import pygame
from pygame import gfxdraw from pygame import gfxdraw
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[box2d]`" "pygame is not installed, run `pip install gymnasium[box2d]`"
) ) from e
if self.screen is None and self.render_mode == "human": if self.screen is None and self.render_mode == "human":
pygame.init() pygame.init()

View File

@@ -294,10 +294,10 @@ class AcrobotEnv(Env):
try: try:
import pygame import pygame
from pygame import gfxdraw from pygame import gfxdraw
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[classic_control]`" "pygame is not installed, run `pip install gymnasium[classic_control]`"
) ) from e
if self.screen is None: if self.screen is None:
pygame.init() pygame.init()

View File

@@ -219,10 +219,10 @@ class CartPoleEnv(gym.Env[np.ndarray, Union[int, np.ndarray]]):
try: try:
import pygame import pygame
from pygame import gfxdraw from pygame import gfxdraw
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[classic_control]`" "pygame is not installed, run `pip install gymnasium[classic_control]`"
) ) from e
if self.screen is None: if self.screen is None:
pygame.init() pygame.init()

View File

@@ -205,10 +205,10 @@ class Continuous_MountainCarEnv(gym.Env):
try: try:
import pygame import pygame
from pygame import gfxdraw from pygame import gfxdraw
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[classic_control]`" "pygame is not installed, run `pip install gymnasium[classic_control]`"
) ) from e
if self.screen is None: if self.screen is None:
pygame.init() pygame.init()

View File

@@ -180,10 +180,10 @@ class MountainCarEnv(gym.Env):
try: try:
import pygame import pygame
from pygame import gfxdraw from pygame import gfxdraw
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[classic_control]`" "pygame is not installed, run `pip install gymnasium[classic_control]`"
) ) from e
if self.screen is None: if self.screen is None:
pygame.init() pygame.init()

View File

@@ -180,10 +180,10 @@ class PendulumEnv(gym.Env):
try: try:
import pygame import pygame
from pygame import gfxdraw from pygame import gfxdraw
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[classic_control]`" "pygame is not installed, run `pip install gymnasium[classic_control]`"
) ) from e
if self.screen is None: if self.screen is None:
pygame.init() pygame.init()

View File

@@ -9,8 +9,9 @@ def verify_number_and_cast(x: SupportsFloat) -> float:
"""Verify parameter is a single number and cast to a float.""" """Verify parameter is a single number and cast to a float."""
try: try:
x = float(x) x = float(x)
except (ValueError, TypeError): except (ValueError, TypeError) as e:
raise ValueError(f"An option ({x}) could not be converted to a float.") raise ValueError(f"An option ({x}) could not be converted to a "
f"float.") from e
return x return x

View File

@@ -158,12 +158,12 @@ class OffScreenViewer(BaseRender):
if self.backend is not None: if self.backend is not None:
try: try:
self.opengl_context = _ALL_RENDERERS[self.backend](width, height) self.opengl_context = _ALL_RENDERERS[self.backend](width, height)
except KeyError: except KeyError as e:
raise RuntimeError( raise RuntimeError(
"Environment variable {} must be one of {!r}: got {!r}.".format( "Environment variable {} must be one of {!r}: got {!r}.".format(
"MUJOCO_GL", _ALL_RENDERERS.keys(), self.backend "MUJOCO_GL", _ALL_RENDERERS.keys(), self.backend
) )
) ) from e
else: else:
for name, _ in _ALL_RENDERERS.items(): for name, _ in _ALL_RENDERERS.items():

View File

@@ -141,10 +141,10 @@ class CartPoleFunctional(
try: try:
import pygame import pygame
from pygame import gfxdraw from pygame import gfxdraw
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[classic_control]`" "pygame is not installed, run `pip install gymnasium[classic_control]`"
) ) from e
screen, clock = render_state screen, clock = render_state
world_width = self.x_threshold * 2 world_width = self.x_threshold * 2
@@ -212,10 +212,10 @@ class CartPoleFunctional(
) -> RenderStateType: ) -> RenderStateType:
try: try:
import pygame import pygame
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[classic_control]`" "pygame is not installed, run `pip install gymnasium[classic_control]`"
) ) from e
pygame.init() pygame.init()
screen = pygame.Surface((screen_width, screen_height)) screen = pygame.Surface((screen_width, screen_height))
@@ -226,10 +226,10 @@ class CartPoleFunctional(
def render_close(self, render_state: RenderStateType) -> None: def render_close(self, render_state: RenderStateType) -> None:
try: try:
import pygame import pygame
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[classic_control]`" "pygame is not installed, run `pip install gymnasium[classic_control]`"
) ) from e
pygame.display.quit() pygame.display.quit()
pygame.quit() pygame.quit()

View File

@@ -90,10 +90,10 @@ class PendulumFunctional(
try: try:
import pygame import pygame
from pygame import gfxdraw from pygame import gfxdraw
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[classic_control]`" "pygame is not installed, run `pip install gymnasium[classic_control]`"
) ) from e
screen, clock, last_u = render_state screen, clock, last_u = render_state
surf = pygame.Surface((self.screen_dim, self.screen_dim)) surf = pygame.Surface((self.screen_dim, self.screen_dim))
@@ -161,10 +161,10 @@ class PendulumFunctional(
) -> RenderStateType: ) -> RenderStateType:
try: try:
import pygame import pygame
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[classic_control]`" "pygame is not installed, run `pip install gymnasium[classic_control]`"
) ) from e
pygame.init() pygame.init()
screen = pygame.Surface((screen_width, screen_height)) screen = pygame.Surface((screen_width, screen_height))
@@ -175,10 +175,10 @@ class PendulumFunctional(
def render_close(self, render_state: RenderStateType) -> None: def render_close(self, render_state: RenderStateType) -> None:
try: try:
import pygame import pygame
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[classic_control]`" "pygame is not installed, run `pip install gymnasium[classic_control]`"
) ) from e
pygame.display.quit() pygame.display.quit()
pygame.quit() pygame.quit()

View File

@@ -563,7 +563,7 @@ def make(
raise ModuleNotFoundError( raise ModuleNotFoundError(
f"{e}. Environment registration via importing a module failed. " f"{e}. Environment registration via importing a module failed. "
f"Check whether '{module}' contains env registration and can be imported." f"Check whether '{module}' contains env registration and can be imported."
) ) from e
spec_ = registry.get(id) spec_ = registry.get(id)
ns, name, version = parse_env_id(id) ns, name, version = parse_env_id(id)
@@ -647,7 +647,7 @@ def make(
f"You passed render_mode='human' although {id} doesn't implement human-rendering natively. " f"You passed render_mode='human' although {id} doesn't implement human-rendering natively. "
"Gym tried to apply the HumanRendering wrapper but it looks like your environment is using the old " "Gym tried to apply the HumanRendering wrapper but it looks like your environment is using the old "
"rendering API, which is not supported by the HumanRendering wrapper." "rendering API, which is not supported by the HumanRendering wrapper."
) ) from e
else: else:
raise e raise e

View File

@@ -235,10 +235,10 @@ class BlackjackEnv(gym.Env):
try: try:
import pygame import pygame
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[toy_text]`" "pygame is not installed, run `pip install gymnasium[toy_text]`"
) ) from e
player_sum, dealer_card_value, usable_ace = self._get_obs() player_sum, dealer_card_value, usable_ace = self._get_obs()
screen_width, screen_height = 600, 500 screen_width, screen_height = 600, 500

View File

@@ -208,10 +208,10 @@ class CliffWalkingEnv(Env):
def _render_gui(self, mode): def _render_gui(self, mode):
try: try:
import pygame import pygame
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[toy_text]`" "pygame is not installed, run `pip install gymnasium[toy_text]`"
) ) from e
if self.window_surface is None: if self.window_surface is None:
pygame.init() pygame.init()

View File

@@ -340,10 +340,10 @@ class FrozenLakeEnv(Env):
def _render_gui(self, mode): def _render_gui(self, mode):
try: try:
import pygame import pygame
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[toy_text]`" "pygame is not installed, run `pip install gymnasium[toy_text]`"
) ) from e
if self.window_surface is None: if self.window_surface is None:
pygame.init() pygame.init()

View File

@@ -325,10 +325,10 @@ class TaxiEnv(Env):
def _render_gui(self, mode): def _render_gui(self, mode):
try: try:
import pygame # dependency to pygame only if rendering with human import pygame # dependency to pygame only if rendering with human
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[toy_text]`" "pygame is not installed, run `pip install gymnasium[toy_text]`"
) ) from e
if self.window is None: if self.window is None:
pygame.init() pygame.init()

View File

@@ -272,10 +272,10 @@ class ResizeObservationV0(LambdaObservationV0):
try: try:
import cv2 import cv2
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"opencv is not install, run `pip install gymnasium[other]`" "opencv is not installed, run `pip install gymnasium[other]`"
) ) from e
self.shape: Final[tuple[int, ...]] = tuple(shape) self.shape: Final[tuple[int, ...]] = tuple(shape)

View File

@@ -113,7 +113,7 @@ def check_reset_seed(env: gym.Env):
raise AssertionError( raise AssertionError(
"The environment cannot be reset with a random seed, even though `seed` or `kwargs` appear in the signature. " "The environment cannot be reset with a random seed, even though `seed` or `kwargs` appear in the signature. "
f"This should never happen, please report this issue. The error was: {e}" f"This should never happen, please report this issue. The error was: {e}"
) ) from e
seed_param = signature.parameters.get("seed") seed_param = signature.parameters.get("seed")
# Check the default value is None # Check the default value is None
@@ -149,7 +149,7 @@ def check_reset_options(env: gym.Env):
raise AssertionError( raise AssertionError(
"The environment cannot be reset with options, even though `options` or `**kwargs` appear in the signature. " "The environment cannot be reset with options, even though `options` or `**kwargs` appear in the signature. "
f"This should never happen, please report this issue. The error was: {e}" f"This should never happen, please report this issue. The error was: {e}"
) ) from e
else: else:
raise gym.error.Error( raise gym.error.Error(
"The `reset` method does not provide an `options` or `**kwargs` keyword argument." "The `reset` method does not provide an `options` or `**kwargs` keyword argument."

View File

@@ -15,10 +15,10 @@ try:
import pygame import pygame
from pygame import Surface from pygame import Surface
from pygame.event import Event from pygame.event import Event
except ImportError: except ImportError as e:
raise gym.error.DependencyNotInstalled( raise gym.error.DependencyNotInstalled(
"Pygame is not installed, run `pip install gymnasium[classic_control]`" "Pygame is not installed, run `pip install gymnasium[classic_control]`"
) ) from e
try: try:
import matplotlib import matplotlib

View File

@@ -8,10 +8,10 @@ from gymnasium import logger
try: try:
from moviepy.video.io.ImageSequenceClip import ImageSequenceClip from moviepy.video.io.ImageSequenceClip import ImageSequenceClip
except ImportError: except ImportError as e:
raise gym.error.DependencyNotInstalled( raise gym.error.DependencyNotInstalled(
"MoviePy is not installed, run `pip install moviepy`" "MoviePy is not installed, run `pip install moviepy`"
) ) from e
def capped_cubic_video_schedule(episode_id: int) -> bool: def capped_cubic_video_schedule(episode_id: int) -> bool:

View File

@@ -123,7 +123,7 @@ class AsyncVectorEnv(VectorEnv):
self.observations = read_from_shared_memory( self.observations = read_from_shared_memory(
self.single_observation_space, _obs_buffer, n=self.num_envs self.single_observation_space, _obs_buffer, n=self.num_envs
) )
except CustomSpaceError: except CustomSpaceError as e:
raise ValueError( raise ValueError(
"Using `shared_memory=True` in `AsyncVectorEnv` " "Using `shared_memory=True` in `AsyncVectorEnv` "
"is incompatible with non-standard Gymnasium observation spaces " "is incompatible with non-standard Gymnasium observation spaces "
@@ -131,7 +131,7 @@ class AsyncVectorEnv(VectorEnv):
"only compatible with default Gymnasium spaces (e.g. `Box`, " "only compatible with default Gymnasium spaces (e.g. `Box`, "
"`Tuple`, `Dict`) for batching. Set `shared_memory=False` " "`Tuple`, `Dict`) for batching. Set `shared_memory=False` "
"if you use custom observation spaces." "if you use custom observation spaces."
) ) from e
else: else:
_obs_buffer = None _obs_buffer = None
self.observations = create_empty_array( self.observations = create_empty_array(

View File

@@ -180,8 +180,9 @@ def _iterate_discrete(space, items):
def _iterate_base(space, items): def _iterate_base(space, items):
try: try:
return iter(items) return iter(items)
except TypeError: except TypeError as e:
raise TypeError(f"Unable to iterate over the following elements: {items}") raise TypeError(f"Unable to iterate over the following elements: "
f"{items}") from e
@iterate.register(Tuple) @iterate.register(Tuple)

View File

@@ -36,10 +36,10 @@ class LazyFrames:
if lz4_compress: if lz4_compress:
try: try:
from lz4.block import compress from lz4.block import compress
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"lz4 is not installed, run `pip install gymnasium[other]`" "lz4 is not installed, run `pip install gymnasium[other]`"
) ) from e
frames = [compress(frame) for frame in frames] frames = [compress(frame) for frame in frames]
self._frames = frames self._frames = frames

View File

@@ -89,10 +89,10 @@ class HumanRendering(gym.Wrapper):
"""Fetch the last frame from the base environment and render it to the screen.""" """Fetch the last frame from the base environment and render it to the screen."""
try: try:
import pygame import pygame
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[box2d]`" "pygame is not installed, run `pip install gymnasium[box2d]`"
) ) from e
if self.env.render_mode == "rgb_array_list": if self.env.render_mode == "rgb_array_list":
last_rgb_array = self.env.render() last_rgb_array = self.env.render()
assert isinstance(last_rgb_array, list) assert isinstance(last_rgb_array, list)

View File

@@ -59,10 +59,10 @@ class ResizeObservation(gym.ObservationWrapper):
""" """
try: try:
import cv2 import cv2
except ImportError: except ImportError as e:
raise DependencyNotInstalled( raise DependencyNotInstalled(
"opencv is not install, run `pip install gymnasium[other]`" "opencv is not installed, run `pip install gymnasium[other]`"
) ) from e
observation = cv2.resize( observation = cv2.resize(
observation, self.shape[::-1], interpolation=cv2.INTER_AREA observation, self.shape[::-1], interpolation=cv2.INTER_AREA