From bf093c689045953e3e1c0c846aeb5d2e2e5e4798 Mon Sep 17 00:00:00 2001 From: Mark Towers Date: Tue, 26 Apr 2022 16:18:37 +0100 Subject: [PATCH] Update the flake8 pre-commit ignores (#2778) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Remove additional ignores from flake8 * Remove all unused imports * Remove all unused imports * Update flake8 and pyupgrade * F841, removed unused variables * E731, removed lambda assignment to variables * Remove E731, F403, F405, F524 * Remove E722, bare exceptions * Remove E712, compare variable == True or == False to is True or is False * Remove E402, module level import not at top of file * Added --pre-file-ignores * Add --per-file-ignores removing E741, E302 and E704 * Add E741, do not use variables named ‘l’, ‘O’, or ‘I’ to ignore issues in classic control * Fixed issues for pytest==6.2 * Remove unnecessary # noqa * Edit comment with the removal of E302 * Added warnings and declared module, attr for pyright type hinting * Remove unused import * Removed flake8 E302 * Updated flake8 from 3.9.2 to 4.0.1 * Remove unused variable --- .pre-commit-config.yaml | 9 +++--- gym/core.py | 1 - gym/envs/box2d/bipedal_walker.py | 6 +--- gym/envs/box2d/car_dynamics.py | 11 +------ gym/envs/box2d/car_racing.py | 5 ++- gym/envs/box2d/lunar_lander.py | 5 ++- gym/envs/classic_control/acrobot.py | 1 - gym/envs/classic_control/cartpole.py | 1 - .../continuous_mountain_car.py | 1 - gym/envs/classic_control/mountain_car.py | 1 - gym/envs/classic_control/pendulum.py | 1 - gym/envs/mujoco/mujoco_env.py | 1 - gym/envs/mujoco/pusher.py | 1 - gym/envs/registration.py | 17 ++++++++-- gym/envs/toy_text/blackjack.py | 1 - gym/envs/toy_text/frozen_lake.py | 1 - gym/error.py | 5 +-- gym/utils/__init__.py | 4 +-- gym/utils/play.py | 1 - gym/utils/seeding.py | 1 - gym/vector/async_vector_env.py | 5 ++- gym/vector/sync_vector_env.py | 4 +-- gym/vector/utils/numpy_utils.py | 1 - gym/vector/utils/shared_memory.py | 4 +-- gym/vector/vector_env.py | 3 +- gym/wrappers/__init__.py | 1 - gym/wrappers/frame_stack.py | 1 - gym/wrappers/monitoring/video_recorder.py | 2 +- gym/wrappers/normalize.py | 2 -- gym/wrappers/order_enforcing.py | 2 -- gym/wrappers/record_episode_statistics.py | 1 - gym/wrappers/record_video.py | 2 +- gym/wrappers/time_aware_observation.py | 2 -- gym/wrappers/time_limit.py | 2 -- setup.py | 2 +- tests/envs/spec_list.py | 6 ++-- tests/envs/test_action_dim_check.py | 2 -- tests/envs/test_atari_legacy_env_specs.py | 8 ++--- tests/envs/test_envs.py | 9 +++--- tests/envs/test_frozenlake_dfs.py | 3 -- tests/envs/test_registration.py | 3 +- tests/spaces/test_spaces.py | 8 ++--- tests/utils/test_play.py | 10 +++--- tests/vector/test_async_vector_env.py | 10 +++--- tests/vector/test_shared_memory.py | 5 ++- tests/vector/test_spaces.py | 2 +- tests/vector/test_vector_env_wrapper.py | 1 - tests/wrappers/nested_dict_test.py | 2 +- tests/wrappers/test_autoreset.py | 32 ++++++++++--------- tests/wrappers/test_clip_action.py | 5 ++- tests/wrappers/test_frame_stack.py | 8 ++--- tests/wrappers/test_order_enforcing.py | 3 -- .../test_record_episode_statistics.py | 1 - tests/wrappers/test_record_video.py | 9 +----- tests/wrappers/test_time_limit.py | 3 -- tests/wrappers/test_transform_observation.py | 4 ++- 56 files changed, 94 insertions(+), 148 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 994fd6172..515f54ac4 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -10,12 +10,13 @@ repos: - id: codespell args: - --ignore-words-list=nd,reacher,thist,ths - - repo: https://gitlab.com/pycqa/flake8 - rev: 3.9.2 + - repo: https://gitlab.com/PyCQA/flake8 + rev: 4.0.1 hooks: - id: flake8 args: - - --ignore=E203,E402,E712,E722,E731,E741,F401,F403,F405,F524,F841,W503,E302,E704 + - '--per-file-ignores=*/__init__.py:F401 gym/envs/registration.py:E704' + - --ignore=E203,W503,E741 - --max-complexity=30 - --max-line-length=456 - --show-source @@ -26,7 +27,7 @@ repos: - id: isort args: ["--profile", "black"] - repo: https://github.com/asottile/pyupgrade - rev: v2.31.0 + rev: v2.32.0 hooks: - id: pyupgrade # TODO: remove `--keep-runtime-typing` option diff --git a/gym/core.py b/gym/core.py index a136a245c..ccecb6632 100644 --- a/gym/core.py +++ b/gym/core.py @@ -3,7 +3,6 @@ from __future__ import annotations from abc import abstractmethod from typing import Generic, Optional, SupportsFloat, Tuple, TypeVar, Union -import gym from gym import spaces from gym.logger import deprecation from gym.utils import seeding diff --git a/gym/envs/box2d/bipedal_walker.py b/gym/envs/box2d/bipedal_walker.py index ee072cf53..39974896d 100644 --- a/gym/envs/box2d/bipedal_walker.py +++ b/gym/envs/box2d/bipedal_walker.py @@ -1,7 +1,6 @@ __credits__ = ["Andrea PIERRÉ"] import math -import sys from typing import Optional import Box2D @@ -17,7 +16,7 @@ from Box2D.b2 import ( import gym from gym import error, spaces -from gym.utils import EzPickle, colorize, seeding +from gym.utils import EzPickle FPS = 50 SCALE = 30.0 # affects how fast-paced the game is, forces should be adjusted as well @@ -422,9 +421,6 @@ class BipedalWalker(gym.Env, EzPickle): self.scroll = 0.0 self.lidar_render = 0 - W = VIEWPORT_W / SCALE - H = VIEWPORT_H / SCALE - self._generate_terrain(self.hardcore) self._generate_clouds() diff --git a/gym/envs/box2d/car_dynamics.py b/gym/envs/box2d/car_dynamics.py index e475f2408..404db6a61 100644 --- a/gym/envs/box2d/car_dynamics.py +++ b/gym/envs/box2d/car_dynamics.py @@ -9,17 +9,8 @@ Created by Oleg Klimov import math -import Box2D import numpy as np -from Box2D.b2 import ( - circleShape, - contactListener, - edgeShape, - fixtureDef, - polygonShape, - revoluteJointDef, - shape, -) +from Box2D.b2 import fixtureDef, polygonShape, revoluteJointDef SIZE = 0.02 ENGINE_POWER = 100000000 * SIZE * SIZE diff --git a/gym/envs/box2d/car_racing.py b/gym/envs/box2d/car_racing.py index de2b18116..8d6b20eb6 100644 --- a/gym/envs/box2d/car_racing.py +++ b/gym/envs/box2d/car_racing.py @@ -1,7 +1,6 @@ __credits__ = ["Andrea PIERRÉ"] import math -import sys from typing import Optional import Box2D @@ -11,7 +10,7 @@ from Box2D.b2 import contactListener, fixtureDef, polygonShape import gym from gym import spaces from gym.envs.box2d.car_dynamics import Car -from gym.utils import EzPickle, seeding +from gym.utils import EzPickle STATE_W = 96 # less than Atari 160x192 STATE_H = 96 @@ -700,6 +699,6 @@ if __name__ == "__main__": print(f"step {steps} total_reward {total_reward:+0.2f}") steps += 1 isopen = env.render() - if done or restart or isopen == False: + if done or restart or isopen is False: break env.close() diff --git a/gym/envs/box2d/lunar_lander.py b/gym/envs/box2d/lunar_lander.py index 1107bb642..fb3175444 100644 --- a/gym/envs/box2d/lunar_lander.py +++ b/gym/envs/box2d/lunar_lander.py @@ -1,7 +1,6 @@ __credits__ = ["Andrea PIERRÉ"] import math -import sys from typing import Optional import Box2D @@ -17,7 +16,7 @@ from Box2D.b2 import ( import gym from gym import error, spaces -from gym.utils import EzPickle, seeding +from gym.utils import EzPickle FPS = 50 SCALE = 30.0 # affects how fast-paced the game is, forces should be adjusted as well @@ -713,7 +712,7 @@ def demo_heuristic_lander(env, seed=None, render=False): if render: still_open = env.render() - if still_open == False: + if still_open is False: break if steps % 20 == 0 or done: diff --git a/gym/envs/classic_control/acrobot.py b/gym/envs/classic_control/acrobot.py index 78b5d0894..63e144ca5 100644 --- a/gym/envs/classic_control/acrobot.py +++ b/gym/envs/classic_control/acrobot.py @@ -5,7 +5,6 @@ import numpy as np from numpy import cos, pi, sin from gym import core, spaces -from gym.utils import seeding __copyright__ = "Copyright 2013, RLPy http://acl.mit.edu/RLPy" __credits__ = [ diff --git a/gym/envs/classic_control/cartpole.py b/gym/envs/classic_control/cartpole.py index 8bb67762f..63c77bffc 100644 --- a/gym/envs/classic_control/cartpole.py +++ b/gym/envs/classic_control/cartpole.py @@ -10,7 +10,6 @@ import numpy as np import gym from gym import logger, spaces -from gym.utils import seeding class CartPoleEnv(gym.Env[np.ndarray, Union[int, np.ndarray]]): diff --git a/gym/envs/classic_control/continuous_mountain_car.py b/gym/envs/classic_control/continuous_mountain_car.py index b7a45e63c..2355f530c 100644 --- a/gym/envs/classic_control/continuous_mountain_car.py +++ b/gym/envs/classic_control/continuous_mountain_car.py @@ -20,7 +20,6 @@ import numpy as np import gym from gym import spaces -from gym.utils import seeding class Continuous_MountainCarEnv(gym.Env): diff --git a/gym/envs/classic_control/mountain_car.py b/gym/envs/classic_control/mountain_car.py index 6c9a555b5..937eba8e1 100644 --- a/gym/envs/classic_control/mountain_car.py +++ b/gym/envs/classic_control/mountain_car.py @@ -9,7 +9,6 @@ import numpy as np import gym from gym import spaces -from gym.utils import seeding class MountainCarEnv(gym.Env): diff --git a/gym/envs/classic_control/pendulum.py b/gym/envs/classic_control/pendulum.py index bd29042de..d77c382ed 100644 --- a/gym/envs/classic_control/pendulum.py +++ b/gym/envs/classic_control/pendulum.py @@ -7,7 +7,6 @@ import numpy as np import gym from gym import spaces -from gym.utils import seeding class PendulumEnv(gym.Env): diff --git a/gym/envs/mujoco/mujoco_env.py b/gym/envs/mujoco/mujoco_env.py index 1d04f2f90..55c3884ac 100644 --- a/gym/envs/mujoco/mujoco_env.py +++ b/gym/envs/mujoco/mujoco_env.py @@ -7,7 +7,6 @@ import numpy as np import gym from gym import error, spaces -from gym.utils import seeding try: import mujoco_py diff --git a/gym/envs/mujoco/pusher.py b/gym/envs/mujoco/pusher.py index 3be870e01..6e20ba42b 100644 --- a/gym/envs/mujoco/pusher.py +++ b/gym/envs/mujoco/pusher.py @@ -1,4 +1,3 @@ -import mujoco_py import numpy as np from gym import utils diff --git a/gym/envs/registration.py b/gym/envs/registration.py index 48b7d6f96..3bd07d654 100644 --- a/gym/envs/registration.py +++ b/gym/envs/registration.py @@ -7,6 +7,7 @@ import importlib import importlib.util import re import sys +import warnings from dataclasses import dataclass, field from typing import ( Any, @@ -225,6 +226,7 @@ def load_env_plugins(entry_point: str = "gym.envs") -> None: for plugin in metadata.entry_points(group=entry_point): # Python 3.8 doesn't support plugin.module, plugin.attr # So we'll have to try and parse this ourselves + module, attr = None, None try: module, attr = plugin.module, plugin.attr # type: ignore ## error: Cannot access member "attr" for type "EntryPoint" except AttributeError: @@ -232,7 +234,10 @@ def load_env_plugins(entry_point: str = "gym.envs") -> None: module, attr = plugin.value.split(":", maxsplit=1) else: module, attr = plugin.value, None - except: + except Exception as e: + warnings.warn( + f"While trying to load plugin `{plugin}` from {entry_point}, an exception occurred: {e}" + ) module, attr = None, None finally: if attr is None: @@ -264,8 +269,12 @@ def load_env_plugins(entry_point: str = "gym.envs") -> None: # fmt: off +# Classic control +# ---------------------------------------- + + @overload -def make(id: Literal["CartPole-v0", "CartPole-v1"], **kwargs) -> Env[np.ndarray, np.ndarray | int]: ... +def make(id: Literal["CartPole-v1"], **kwargs) -> Env[np.ndarray, np.ndarray | int]: ... @overload def make(id: Literal["MountainCar-v0"], **kwargs) -> Env[np.ndarray, np.ndarray | int]: ... @overload @@ -278,6 +287,7 @@ def make(id: Literal["Acrobot-v1"], **kwargs) -> Env[np.ndarray, np.ndarray | in # Box2d # ---------------------------------------- + @overload def make(id: Literal["LunarLander-v2", "LunarLanderContinuous-v2"], **kwargs) -> Env[np.ndarray, np.ndarray | int]: ... @overload @@ -288,6 +298,7 @@ def make(id: Literal["CarRacing-v1", "CarRacingDomainRandomize-v1"], **kwargs) - # Toy Text # ---------------------------------------- + @overload def make(id: Literal["Blackjack-v1"], **kwargs) -> Env[np.ndarray, np.ndarray | int]: ... @overload @@ -299,6 +310,8 @@ def make(id: Literal["Taxi-v3"], **kwargs) -> Env[np.ndarray, np.ndarray | int]: # Mujoco # ---------------------------------------- + + @overload def make(id: Literal[ "Reacher-v2", diff --git a/gym/envs/toy_text/blackjack.py b/gym/envs/toy_text/blackjack.py index fa3849615..271dfe8b9 100644 --- a/gym/envs/toy_text/blackjack.py +++ b/gym/envs/toy_text/blackjack.py @@ -5,7 +5,6 @@ import numpy as np import gym from gym import spaces -from gym.utils import seeding def cmp(a, b): diff --git a/gym/envs/toy_text/frozen_lake.py b/gym/envs/toy_text/frozen_lake.py index f08d60b2f..f5319a19d 100644 --- a/gym/envs/toy_text/frozen_lake.py +++ b/gym/envs/toy_text/frozen_lake.py @@ -242,7 +242,6 @@ class FrozenLakeEnv(Env): def _render_gui(self, desc, mode): import pygame - from pygame.constants import SRCALPHA if self.window_surface is None: pygame.init() diff --git a/gym/error.py b/gym/error.py index 4a28b9609..f83d362a2 100644 --- a/gym/error.py +++ b/gym/error.py @@ -1,6 +1,3 @@ -import sys - - class Error(Exception): pass @@ -133,7 +130,7 @@ class APIError(Error): if http_body and hasattr(http_body, "decode"): try: http_body = http_body.decode("utf-8") - except: + except Exception: http_body = "" self._message = message diff --git a/gym/utils/__init__.py b/gym/utils/__init__.py index e01a19841..189cd574e 100644 --- a/gym/utils/__init__.py +++ b/gym/utils/__init__.py @@ -5,5 +5,5 @@ not intended as API functions, and will not remain stable over time. # These submodules should not have any import-time dependencies. # We want this since we use `utils` during our import-time sanity checks # that verify that our dependencies are actually present. -from .colorize import colorize -from .ezpickle import EzPickle +from gym.utils.colorize import colorize +from gym.utils.ezpickle import EzPickle diff --git a/gym/utils/play.py b/gym/utils/play.py index f04ccae4a..8e0d01800 100644 --- a/gym/utils/play.py +++ b/gym/utils/play.py @@ -5,7 +5,6 @@ from numpy.typing import NDArray from pygame import Surface from pygame.event import Event -import gym from gym import Env, logger try: diff --git a/gym/utils/seeding.py b/gym/utils/seeding.py index 4d29b3d66..c1986ba60 100644 --- a/gym/utils/seeding.py +++ b/gym/utils/seeding.py @@ -4,7 +4,6 @@ import struct from typing import Any, List, Optional, Tuple, Union import numpy as np -from numpy.random import Generator from gym import error from gym.logger import deprecation diff --git a/gym/vector/async_vector_env.py b/gym/vector/async_vector_env.py index e9c1c99f4..565c75137 100644 --- a/gym/vector/async_vector_env.py +++ b/gym/vector/async_vector_env.py @@ -14,7 +14,6 @@ from gym.error import ( CustomSpaceError, NoAsyncCallError, ) -from gym.logger import warn from gym.vector.utils import ( CloudpickleWrapper, clear_mpi_env_vars, @@ -639,7 +638,7 @@ def _worker(index, env_fn, pipe, parent_pipe, shared_memory, error_queue): while True: command, data = pipe.recv() if command == "reset": - if "return_info" in data and data["return_info"] == True: + if "return_info" in data and data["return_info"] is True: observation, info = env.reset(**data) pipe.send(((observation, info), True)) else: @@ -703,7 +702,7 @@ def _worker_shared_memory(index, env_fn, pipe, parent_pipe, shared_memory, error while True: command, data = pipe.recv() if command == "reset": - if "return_info" in data and data["return_info"] == True: + if "return_info" in data and data["return_info"] is True: observation, info = env.reset(**data) write_to_shared_memory( observation_space, index, observation, shared_memory diff --git a/gym/vector/sync_vector_env.py b/gym/vector/sync_vector_env.py index 97913499b..dc2e8c345 100644 --- a/gym/vector/sync_vector_env.py +++ b/gym/vector/sync_vector_env.py @@ -3,8 +3,6 @@ from typing import List, Optional, Union import numpy as np -from gym import logger -from gym.logger import warn from gym.vector.utils import concatenate, create_empty_array, iterate from gym.vector.vector_env import VectorEnv @@ -108,7 +106,7 @@ class SyncVectorEnv(VectorEnv): kwargs["seed"] = single_seed if options is not None: kwargs["options"] = options - if return_info == True: + if return_info is True: kwargs["return_info"] = return_info if not return_info: diff --git a/gym/vector/utils/numpy_utils.py b/gym/vector/utils/numpy_utils.py index 6ea257618..af6295cf5 100644 --- a/gym/vector/utils/numpy_utils.py +++ b/gym/vector/utils/numpy_utils.py @@ -4,7 +4,6 @@ from functools import singledispatch import numpy as np from gym.spaces import Box, Dict, Discrete, MultiBinary, MultiDiscrete, Space, Tuple -from gym.vector.utils.spaces import _BaseGymSpaces __all__ = ["concatenate", "create_empty_array"] diff --git a/gym/vector/utils/shared_memory.py b/gym/vector/utils/shared_memory.py index 497caeb4c..dd0c9beb6 100644 --- a/gym/vector/utils/shared_memory.py +++ b/gym/vector/utils/shared_memory.py @@ -5,10 +5,8 @@ from functools import singledispatch import numpy as np -from gym import logger from gym.error import CustomSpaceError -from gym.spaces import Box, Dict, Discrete, MultiBinary, MultiDiscrete, Space, Tuple -from gym.vector.utils.spaces import _BaseGymSpaces +from gym.spaces import Box, Dict, Discrete, MultiBinary, MultiDiscrete, Tuple __all__ = ["create_shared_memory", "read_from_shared_memory", "write_to_shared_memory"] diff --git a/gym/vector/vector_env.py b/gym/vector/vector_env.py index 06fd48583..2c5e00e78 100644 --- a/gym/vector/vector_env.py +++ b/gym/vector/vector_env.py @@ -1,8 +1,7 @@ from typing import List, Optional, Union import gym -from gym.logger import deprecation, warn -from gym.spaces import Tuple +from gym.logger import deprecation from gym.vector.utils.spaces import batch_space __all__ = ["VectorEnv"] diff --git a/gym/wrappers/__init__.py b/gym/wrappers/__init__.py index caadb4074..035ecf24c 100644 --- a/gym/wrappers/__init__.py +++ b/gym/wrappers/__init__.py @@ -1,4 +1,3 @@ -from gym import error from gym.wrappers.atari_preprocessing import AtariPreprocessing from gym.wrappers.autoreset import AutoResetWrapper from gym.wrappers.clip_action import ClipAction diff --git a/gym/wrappers/frame_stack.py b/gym/wrappers/frame_stack.py index 0af589bdf..8e4a66519 100644 --- a/gym/wrappers/frame_stack.py +++ b/gym/wrappers/frame_stack.py @@ -1,5 +1,4 @@ from collections import deque -from typing import Optional import numpy as np diff --git a/gym/wrappers/monitoring/video_recorder.py b/gym/wrappers/monitoring/video_recorder.py index f9a8b717e..95622e0cc 100644 --- a/gym/wrappers/monitoring/video_recorder.py +++ b/gym/wrappers/monitoring/video_recorder.py @@ -418,7 +418,7 @@ class ImageEncoder: try: self.proc.stdin.write(frame.tobytes()) - except Exception as e: + except Exception: stdout, stderr = self.proc.communicate() logger.error("VideoRecorder encoder failed: %s", stderr) diff --git a/gym/wrappers/normalize.py b/gym/wrappers/normalize.py index d12a87a2a..38a03f46b 100644 --- a/gym/wrappers/normalize.py +++ b/gym/wrappers/normalize.py @@ -1,5 +1,3 @@ -from typing import Optional - import numpy as np import gym diff --git a/gym/wrappers/order_enforcing.py b/gym/wrappers/order_enforcing.py index f6f33fa5c..54c09ff5e 100644 --- a/gym/wrappers/order_enforcing.py +++ b/gym/wrappers/order_enforcing.py @@ -1,5 +1,3 @@ -from typing import Optional - import gym diff --git a/gym/wrappers/record_episode_statistics.py b/gym/wrappers/record_episode_statistics.py index ab5f51192..5bf6fe5c3 100644 --- a/gym/wrappers/record_episode_statistics.py +++ b/gym/wrappers/record_episode_statistics.py @@ -1,6 +1,5 @@ import time from collections import deque -from typing import Optional import numpy as np diff --git a/gym/wrappers/record_video.py b/gym/wrappers/record_video.py index dd2efa295..459f5d0d0 100644 --- a/gym/wrappers/record_video.py +++ b/gym/wrappers/record_video.py @@ -1,5 +1,5 @@ import os -from typing import Callable, Optional +from typing import Callable import gym from gym import logger diff --git a/gym/wrappers/time_aware_observation.py b/gym/wrappers/time_aware_observation.py index a61d14744..7f22e6814 100644 --- a/gym/wrappers/time_aware_observation.py +++ b/gym/wrappers/time_aware_observation.py @@ -1,5 +1,3 @@ -from typing import Optional - import numpy as np from gym import ObservationWrapper diff --git a/gym/wrappers/time_limit.py b/gym/wrappers/time_limit.py index 43c9f9a60..d799341f9 100644 --- a/gym/wrappers/time_limit.py +++ b/gym/wrappers/time_limit.py @@ -1,5 +1,3 @@ -from typing import Optional - import gym diff --git a/setup.py b/setup.py index a4317a7bb..05f989daf 100644 --- a/setup.py +++ b/setup.py @@ -6,7 +6,7 @@ from setuptools import find_packages, setup # Don't import gym module here, since deps may not be installed sys.path.insert(0, os.path.join(os.path.dirname(__file__), "gym")) -from version import VERSION +from version import VERSION # noqa:E402 # Environment-specific dependencies. extras = { diff --git a/tests/envs/spec_list.py b/tests/envs/spec_list.py index 289d38f2e..a0f192b7c 100644 --- a/tests/envs/spec_list.py +++ b/tests/envs/spec_list.py @@ -11,7 +11,7 @@ SKIP_MUJOCO_WARNING_MESSAGE = ( skip_mujoco = not (os.environ.get("MUJOCO_KEY")) if not skip_mujoco: try: - import mujoco_py + import mujoco_py # noqa:F401 except ImportError: skip_mujoco = True @@ -24,12 +24,12 @@ def should_skip_env_spec_for_tests(spec): if skip_mujoco and ep.startswith("gym.envs.mujoco"): return True try: - import gym.envs.atari + import gym.envs.atari # noqa:F401 except ImportError: if ep.startswith("gym.envs.atari"): return True try: - import Box2D + import Box2D # noqa:F401 except ImportError: if ep.startswith("gym.envs.box2d"): return True diff --git a/tests/envs/test_action_dim_check.py b/tests/envs/test_action_dim_check.py index 448847cd6..a64792408 100644 --- a/tests/envs/test_action_dim_check.py +++ b/tests/envs/test_action_dim_check.py @@ -1,5 +1,3 @@ -import pickle - import pytest from gym import envs diff --git a/tests/envs/test_atari_legacy_env_specs.py b/tests/envs/test_atari_legacy_env_specs.py index 37e99245c..5a1c406e4 100644 --- a/tests/envs/test_atari_legacy_env_specs.py +++ b/tests/envs/test_atari_legacy_env_specs.py @@ -1,11 +1,11 @@ -import pytest - -pytest.importorskip("gym.envs.atari") - from itertools import product +import pytest + from gym.envs.registration import registry +pytest.importorskip("gym.envs.atari") + def test_ale_legacy_env_specs(): versions = ["-v0", "-v4"] diff --git a/tests/envs/test_envs.py b/tests/envs/test_envs.py index 23de61b98..b0a33da2e 100644 --- a/tests/envs/test_envs.py +++ b/tests/envs/test_envs.py @@ -61,7 +61,7 @@ def test_env(spec): @pytest.mark.parametrize("spec", spec_list, ids=[spec.id for spec in spec_list]) def test_reset_info(spec): - with pytest.warns(None) as warnings: + with pytest.warns(None): env = spec.make() ob_space = env.observation_space @@ -78,13 +78,12 @@ def test_reset_info(spec): # Run a longer rollout on some environments def test_random_rollout(): for env in [envs.make("CartPole-v1"), envs.make("FrozenLake-v1")]: - agent = lambda ob: env.action_space.sample() ob = env.reset() for _ in range(10): assert env.observation_space.contains(ob) - a = agent(ob) - assert env.action_space.contains(a) - (ob, _reward, done, _info) = env.step(a) + action = env.action_space.sample() + assert env.action_space.contains(action) + (ob, _reward, done, _info) = env.step(action) if done: break env.close() diff --git a/tests/envs/test_frozenlake_dfs.py b/tests/envs/test_frozenlake_dfs.py index 3cfeddf2b..b620cbcb0 100644 --- a/tests/envs/test_frozenlake_dfs.py +++ b/tests/envs/test_frozenlake_dfs.py @@ -1,6 +1,3 @@ -import numpy as np -import pytest - from gym.envs.toy_text.frozen_lake import generate_random_map diff --git a/tests/envs/test_registration.py b/tests/envs/test_registration.py index be7e856c7..707f0ee04 100644 --- a/tests/envs/test_registration.py +++ b/tests/envs/test_registration.py @@ -2,9 +2,8 @@ import pytest import gym from gym import envs, error -from gym.envs import register, registration, registry, spec +from gym.envs import register, spec from gym.envs.classic_control import cartpole -from gym.envs.registration import EnvSpec class ArgumentEnv(gym.Env): diff --git a/tests/spaces/test_spaces.py b/tests/spaces/test_spaces.py index 975fffa2a..85739028e 100644 --- a/tests/spaces/test_spaces.py +++ b/tests/spaces/test_spaces.py @@ -569,20 +569,20 @@ def test_infinite_space(space): # but floats are unbounded for infinite if np.any(space.high != 0): assert ( - space.is_bounded("above") == False + space.is_bounded("above") is False ), "inf upper bound supposed to be unbounded" else: assert ( - space.is_bounded("above") == True + space.is_bounded("above") is True ), "non-inf upper bound supposed to be bounded" if np.any(space.low != 0): assert ( - space.is_bounded("below") == False + space.is_bounded("below") is False ), "inf lower bound supposed to be unbounded" else: assert ( - space.is_bounded("below") == True + space.is_bounded("below") is True ), "non-inf lower bound supposed to be bounded" # check for dtype diff --git a/tests/utils/test_play.py b/tests/utils/test_play.py index 3719df3b4..02acce160 100644 --- a/tests/utils/test_play.py +++ b/tests/utils/test_play.py @@ -67,7 +67,7 @@ def test_play_relevant_keys_no_mapping(): env = DummyPlayEnv() env.spec = DummyEnvSpec("DummyPlayEnv") - with pytest.raises(MissingKeysToAction) as info: + with pytest.raises(MissingKeysToAction): PlayableGame(env) @@ -96,18 +96,18 @@ def test_keyboard_quit_event(): env = DummyPlayEnv() game = PlayableGame(env, dummy_keys_to_action()) event = Event(pygame.KEYDOWN, {"key": pygame.K_ESCAPE}) - assert game.running == True + assert game.running is True game.process_event(event) - assert game.running == False + assert game.running is False def test_pygame_quit_event(): env = DummyPlayEnv() game = PlayableGame(env, dummy_keys_to_action()) event = Event(pygame.QUIT) - assert game.running == True + assert game.running is True game.process_event(event) - assert game.running == False + assert game.running is False def test_keyboard_relevant_keydown_event(): diff --git a/tests/vector/test_async_vector_env.py b/tests/vector/test_async_vector_env.py index 411047990..a02f0617b 100644 --- a/tests/vector/test_async_vector_env.py +++ b/tests/vector/test_async_vector_env.py @@ -167,7 +167,7 @@ def test_reset_timeout_async_vector_env(shared_memory): try: env = AsyncVectorEnv(env_fns, shared_memory=shared_memory) env.reset_async() - observations = env.reset_wait(timeout=0.1) + env.reset_wait(timeout=0.1) finally: env.close(terminate=True) @@ -178,7 +178,7 @@ def test_step_timeout_async_vector_env(shared_memory): with pytest.raises(TimeoutError): try: env = AsyncVectorEnv(env_fns, shared_memory=shared_memory) - observations = env.reset() + env.reset() env.step_async([0.1, 0.1, 0.3, 0.1]) observations, rewards, dones, _ = env.step_wait(timeout=0.1) finally: @@ -192,7 +192,7 @@ def test_reset_out_of_order_async_vector_env(shared_memory): with pytest.raises(NoAsyncCallError): try: env = AsyncVectorEnv(env_fns, shared_memory=shared_memory) - observations = env.reset_wait() + env.reset_wait() except NoAsyncCallError as exception: assert exception.name == "reset" raise @@ -203,7 +203,7 @@ def test_reset_out_of_order_async_vector_env(shared_memory): try: env = AsyncVectorEnv(env_fns, shared_memory=shared_memory) actions = env.action_space.sample() - observations = env.reset() + env.reset() env.step_async(actions) env.reset_async() except NoAsyncCallError as exception: @@ -248,7 +248,7 @@ def test_already_closed_async_vector_env(shared_memory): with pytest.raises(ClosedEnvironmentError): env = AsyncVectorEnv(env_fns, shared_memory=shared_memory) env.close() - observations = env.reset() + env.reset() @pytest.mark.parametrize("shared_memory", [True, False]) diff --git a/tests/vector/test_shared_memory.py b/tests/vector/test_shared_memory.py index 9c3f6d42a..5d18452a8 100644 --- a/tests/vector/test_shared_memory.py +++ b/tests/vector/test_shared_memory.py @@ -65,8 +65,7 @@ def test_create_shared_memory(space, expected_type, n, ctx): # Assert the length of the array assert len(lhs[:]) == n * len(rhs[:]) # Assert the data type - assert type(lhs[0]) == type(rhs[0]) # noqa: E721 - + assert isinstance(lhs[0], type(rhs[0])) else: raise TypeError(f"Got unknown type `{type(lhs)}`.") @@ -83,7 +82,7 @@ def test_create_shared_memory(space, expected_type, n, ctx): def test_create_shared_memory_custom_space(n, ctx, space): ctx = mp if (ctx is None) else mp.get_context(ctx) with pytest.raises(CustomSpaceError): - shared_memory = create_shared_memory(space, n=n, ctx=ctx) + create_shared_memory(space, n=n, ctx=ctx) @pytest.mark.parametrize( diff --git a/tests/vector/test_spaces.py b/tests/vector/test_spaces.py index 11552b0f4..fa7aee0b4 100644 --- a/tests/vector/test_spaces.py +++ b/tests/vector/test_spaces.py @@ -5,7 +5,7 @@ import pytest from numpy.testing import assert_array_equal from gym import Space -from gym.spaces import Box, Dict, Discrete, MultiDiscrete, Tuple +from gym.spaces import Box, Dict, MultiDiscrete, Tuple from gym.vector.utils.spaces import batch_space, iterate from tests.vector.utils import CustomSpace, assert_rng_equal, custom_spaces, spaces diff --git a/tests/vector/test_vector_env_wrapper.py b/tests/vector/test_vector_env_wrapper.py index 4c8d165d1..156eaa47f 100644 --- a/tests/vector/test_vector_env_wrapper.py +++ b/tests/vector/test_vector_env_wrapper.py @@ -1,4 +1,3 @@ -import gym from gym.vector import VectorEnvWrapper, make diff --git a/tests/wrappers/nested_dict_test.py b/tests/wrappers/nested_dict_test.py index bde470541..87899724e 100644 --- a/tests/wrappers/nested_dict_test.py +++ b/tests/wrappers/nested_dict_test.py @@ -5,7 +5,7 @@ import numpy as np import pytest import gym -from gym.spaces import Box, Dict, Discrete, Tuple +from gym.spaces import Box, Dict, Tuple from gym.wrappers import FilterObservation, FlattenObservation diff --git a/tests/wrappers/test_autoreset.py b/tests/wrappers/test_autoreset.py index 76c035f87..39b47c756 100644 --- a/tests/wrappers/test_autoreset.py +++ b/tests/wrappers/test_autoreset.py @@ -1,4 +1,3 @@ -import types from typing import Optional from unittest.mock import MagicMock @@ -23,7 +22,9 @@ class DummyResetEnv(gym.Env): metadata = {} def __init__(self): - self.action_space = gym.spaces.Box(low=np.array([-1.0]), high=np.array([1.0])) + self.action_space = gym.spaces.Box( + low=np.array([-1.0]), high=np.array([1.0]), dtype=np.float64 + ) self.observation_space = gym.spaces.Box( low=np.array([-1.0]), high=np.array([1.0]) ) @@ -63,6 +64,7 @@ def test_autoreset_reset_info(): obs, info = env.reset(return_info=True) assert ob_space.contains(obs) assert isinstance(info, dict) + env.close() @pytest.mark.parametrize("spec", spec_list, ids=[spec.id for spec in spec_list]) @@ -74,12 +76,10 @@ def test_make_autoreset_true(spec): Note: This test assumes that all first-party environments will terminate in a finite amount of time with random actions, which is true as of the time of adding this test. """ - env = None - with pytest.warns(None) as warnings: + with pytest.warns(None): env = spec.make(autoreset=True) - ob_space = env.observation_space - obs = env.reset(seed=0) + env.reset(seed=0) env.action_space.seed(0) env.unwrapped.reset = MagicMock(side_effect=env.unwrapped.reset) @@ -90,22 +90,23 @@ def test_make_autoreset_true(spec): assert isinstance(env, AutoResetWrapper) assert env.unwrapped.reset.called + env.close() @pytest.mark.parametrize("spec", spec_list, ids=[spec.id for spec in spec_list]) def test_make_autoreset_false(spec): - env = None - with pytest.warns(None) as warnings: + with pytest.warns(None): env = spec.make(autoreset=False) assert not isinstance(env, AutoResetWrapper) + env.close() @pytest.mark.parametrize("spec", spec_list, ids=[spec.id for spec in spec_list]) def test_make_autoreset_default_false(spec): - env = None - with pytest.warns(None) as warnings: + with pytest.warns(None): env = spec.make() assert not isinstance(env, AutoResetWrapper) + env.close() def test_autoreset_autoreset(): @@ -118,16 +119,16 @@ def test_autoreset_autoreset(): obs, reward, done, info = env.step(action) assert obs == np.array([1]) assert reward == 0 - assert done == False + assert done is False assert info == {"count": 1} obs, reward, done, info = env.step(action) assert obs == np.array([2]) - assert done == False + assert done is False assert reward == 0 assert info == {"count": 2} obs, reward, done, info = env.step(action) assert obs == np.array([0]) - assert done == True + assert done is True assert reward == 1 assert info == { "count": 0, @@ -137,10 +138,11 @@ def test_autoreset_autoreset(): obs, reward, done, info = env.step(action) assert obs == np.array([1]) assert reward == 0 - assert done == False + assert done is False assert info == {"count": 1} obs, reward, done, info = env.step(action) assert obs == np.array([2]) assert reward == 0 - assert done == False + assert done is False assert info == {"count": 2} + env.close() diff --git a/tests/wrappers/test_clip_action.py b/tests/wrappers/test_clip_action.py index aebf867b6..d00290f1b 100644 --- a/tests/wrappers/test_clip_action.py +++ b/tests/wrappers/test_clip_action.py @@ -6,9 +6,8 @@ from gym.wrappers import ClipAction def test_clip_action(): # mountaincar: action-based rewards - make_env = lambda: gym.make("MountainCarContinuous-v0") - env = make_env() - wrapped_env = ClipAction(make_env()) + env = gym.make("MountainCarContinuous-v0") + wrapped_env = ClipAction(gym.make("MountainCarContinuous-v0")) seed = 0 diff --git a/tests/wrappers/test_frame_stack.py b/tests/wrappers/test_frame_stack.py index b9af3002c..4c0bdd88d 100644 --- a/tests/wrappers/test_frame_stack.py +++ b/tests/wrappers/test_frame_stack.py @@ -1,8 +1,5 @@ -import pytest - -pytest.importorskip("gym.envs.atari") - import numpy as np +import pytest import gym from gym.wrappers import FrameStack @@ -13,6 +10,9 @@ except ImportError: lz4 = None +pytest.importorskip("gym.envs.atari") + + @pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v1", "Pong-v0"]) @pytest.mark.parametrize("num_stack", [2, 3, 4]) @pytest.mark.parametrize( diff --git a/tests/wrappers/test_order_enforcing.py b/tests/wrappers/test_order_enforcing.py index 9b9290aec..47dd45971 100644 --- a/tests/wrappers/test_order_enforcing.py +++ b/tests/wrappers/test_order_enforcing.py @@ -1,6 +1,3 @@ -import numpy as np -import pytest - import gym from gym.wrappers import OrderEnforcing diff --git a/tests/wrappers/test_record_episode_statistics.py b/tests/wrappers/test_record_episode_statistics.py index d9633409e..4b1598775 100644 --- a/tests/wrappers/test_record_episode_statistics.py +++ b/tests/wrappers/test_record_episode_statistics.py @@ -1,4 +1,3 @@ -import numpy as np import pytest import gym diff --git a/tests/wrappers/test_record_video.py b/tests/wrappers/test_record_video.py index 0757c1bec..2627c6668 100644 --- a/tests/wrappers/test_record_video.py +++ b/tests/wrappers/test_record_video.py @@ -1,15 +1,8 @@ import os import shutil -import numpy as np -import pytest - import gym -from gym.wrappers import ( - RecordEpisodeStatistics, - RecordVideo, - capped_cubic_video_schedule, -) +from gym.wrappers import capped_cubic_video_schedule def test_record_video_using_default_trigger(): diff --git a/tests/wrappers/test_time_limit.py b/tests/wrappers/test_time_limit.py index 32e6e5d2a..fa7f70da4 100644 --- a/tests/wrappers/test_time_limit.py +++ b/tests/wrappers/test_time_limit.py @@ -1,6 +1,3 @@ -import numpy as np -import pytest - import gym from gym.wrappers import TimeLimit diff --git a/tests/wrappers/test_transform_observation.py b/tests/wrappers/test_transform_observation.py index fc1076ae4..695edce07 100644 --- a/tests/wrappers/test_transform_observation.py +++ b/tests/wrappers/test_transform_observation.py @@ -7,7 +7,9 @@ from gym.wrappers import TransformObservation @pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v1"]) def test_transform_observation(env_id): - affine_transform = lambda x: 3 * x + 2 + def affine_transform(x): + return 3 * x + 2 + env = gym.make(env_id) wrapped_env = TransformObservation( gym.make(env_id), lambda obs: affine_transform(obs)