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

View File

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

View File

@@ -15,20 +15,20 @@ from gymnasium.utils import EzPickle
try:
import Box2D
from Box2D.b2 import contactListener, fixtureDef, polygonShape
except ImportError:
except ImportError as e:
raise DependencyNotInstalled(
"box2D is not installed, run `pip install gymnasium[box2d]`"
)
) from e
try:
# 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.
import pygame
from pygame import gfxdraw
except ImportError:
except ImportError as e:
raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[box2d]`"
)
) from e
STATE_W = 96 # less than Atari 160x192

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -180,10 +180,10 @@ class PendulumEnv(gym.Env):
try:
import pygame
from pygame import gfxdraw
except ImportError:
except ImportError as e:
raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[classic_control]`"
)
) from e
if self.screen is None:
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."""
try:
x = float(x)
except (ValueError, TypeError):
raise ValueError(f"An option ({x}) could not be converted to a float.")
except (ValueError, TypeError) as e:
raise ValueError(f"An option ({x}) could not be converted to a "
f"float.") from e
return x

View File

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

View File

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

View File

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

View File

@@ -563,7 +563,7 @@ def make(
raise ModuleNotFoundError(
f"{e}. Environment registration via importing a module failed. "
f"Check whether '{module}' contains env registration and can be imported."
)
) from e
spec_ = registry.get(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. "
"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."
)
) from e
else:
raise e

View File

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

View File

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

View File

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

View File

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

View File

@@ -272,10 +272,10 @@ class ResizeObservationV0(LambdaObservationV0):
try:
import cv2
except ImportError:
except ImportError as e:
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)

View File

@@ -113,7 +113,7 @@ def check_reset_seed(env: gym.Env):
raise AssertionError(
"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}"
)
) from e
seed_param = signature.parameters.get("seed")
# Check the default value is None
@@ -149,7 +149,7 @@ def check_reset_options(env: gym.Env):
raise AssertionError(
"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}"
)
) from e
else:
raise gym.error.Error(
"The `reset` method does not provide an `options` or `**kwargs` keyword argument."

View File

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

View File

@@ -8,10 +8,10 @@ from gymnasium import logger
try:
from moviepy.video.io.ImageSequenceClip import ImageSequenceClip
except ImportError:
except ImportError as e:
raise gym.error.DependencyNotInstalled(
"MoviePy is not installed, run `pip install moviepy`"
)
) from e
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.single_observation_space, _obs_buffer, n=self.num_envs
)
except CustomSpaceError:
except CustomSpaceError as e:
raise ValueError(
"Using `shared_memory=True` in `AsyncVectorEnv` "
"is incompatible with non-standard Gymnasium observation spaces "
@@ -131,7 +131,7 @@ class AsyncVectorEnv(VectorEnv):
"only compatible with default Gymnasium spaces (e.g. `Box`, "
"`Tuple`, `Dict`) for batching. Set `shared_memory=False` "
"if you use custom observation spaces."
)
) from e
else:
_obs_buffer = None
self.observations = create_empty_array(

View File

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

View File

@@ -36,10 +36,10 @@ class LazyFrames:
if lz4_compress:
try:
from lz4.block import compress
except ImportError:
except ImportError as e:
raise DependencyNotInstalled(
"lz4 is not installed, run `pip install gymnasium[other]`"
)
) from e
frames = [compress(frame) for frame in 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."""
try:
import pygame
except ImportError:
except ImportError as e:
raise DependencyNotInstalled(
"pygame is not installed, run `pip install gymnasium[box2d]`"
)
) from e
if self.env.render_mode == "rgb_array_list":
last_rgb_array = self.env.render()
assert isinstance(last_rgb_array, list)

View File

@@ -59,10 +59,10 @@ class ResizeObservation(gym.ObservationWrapper):
"""
try:
import cv2
except ImportError:
except ImportError as e:
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, self.shape[::-1], interpolation=cv2.INTER_AREA