Update the flake8 pre-commit ignores (#2778)

* 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
This commit is contained in:
Mark Towers
2022-04-26 16:18:37 +01:00
committed by GitHub
parent 4ecc2ad35a
commit bf093c6890
56 changed files with 94 additions and 148 deletions

View File

@@ -10,12 +10,13 @@ repos:
- id: codespell - id: codespell
args: args:
- --ignore-words-list=nd,reacher,thist,ths - --ignore-words-list=nd,reacher,thist,ths
- repo: https://gitlab.com/pycqa/flake8 - repo: https://gitlab.com/PyCQA/flake8
rev: 3.9.2 rev: 4.0.1
hooks: hooks:
- id: flake8 - id: flake8
args: 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-complexity=30
- --max-line-length=456 - --max-line-length=456
- --show-source - --show-source
@@ -26,7 +27,7 @@ repos:
- id: isort - id: isort
args: ["--profile", "black"] args: ["--profile", "black"]
- repo: https://github.com/asottile/pyupgrade - repo: https://github.com/asottile/pyupgrade
rev: v2.31.0 rev: v2.32.0
hooks: hooks:
- id: pyupgrade - id: pyupgrade
# TODO: remove `--keep-runtime-typing` option # TODO: remove `--keep-runtime-typing` option

View File

@@ -3,7 +3,6 @@ from __future__ import annotations
from abc import abstractmethod from abc import abstractmethod
from typing import Generic, Optional, SupportsFloat, Tuple, TypeVar, Union from typing import Generic, Optional, SupportsFloat, Tuple, TypeVar, Union
import gym
from gym import spaces from gym import spaces
from gym.logger import deprecation from gym.logger import deprecation
from gym.utils import seeding from gym.utils import seeding

View File

@@ -1,7 +1,6 @@
__credits__ = ["Andrea PIERRÉ"] __credits__ = ["Andrea PIERRÉ"]
import math import math
import sys
from typing import Optional from typing import Optional
import Box2D import Box2D
@@ -17,7 +16,7 @@ from Box2D.b2 import (
import gym import gym
from gym import error, spaces from gym import error, spaces
from gym.utils import EzPickle, colorize, seeding from gym.utils import EzPickle
FPS = 50 FPS = 50
SCALE = 30.0 # affects how fast-paced the game is, forces should be adjusted as well 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.scroll = 0.0
self.lidar_render = 0 self.lidar_render = 0
W = VIEWPORT_W / SCALE
H = VIEWPORT_H / SCALE
self._generate_terrain(self.hardcore) self._generate_terrain(self.hardcore)
self._generate_clouds() self._generate_clouds()

View File

@@ -9,17 +9,8 @@ Created by Oleg Klimov
import math import math
import Box2D
import numpy as np import numpy as np
from Box2D.b2 import ( from Box2D.b2 import fixtureDef, polygonShape, revoluteJointDef
circleShape,
contactListener,
edgeShape,
fixtureDef,
polygonShape,
revoluteJointDef,
shape,
)
SIZE = 0.02 SIZE = 0.02
ENGINE_POWER = 100000000 * SIZE * SIZE ENGINE_POWER = 100000000 * SIZE * SIZE

View File

@@ -1,7 +1,6 @@
__credits__ = ["Andrea PIERRÉ"] __credits__ = ["Andrea PIERRÉ"]
import math import math
import sys
from typing import Optional from typing import Optional
import Box2D import Box2D
@@ -11,7 +10,7 @@ from Box2D.b2 import contactListener, fixtureDef, polygonShape
import gym import gym
from gym import spaces from gym import spaces
from gym.envs.box2d.car_dynamics import Car 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_W = 96 # less than Atari 160x192
STATE_H = 96 STATE_H = 96
@@ -700,6 +699,6 @@ if __name__ == "__main__":
print(f"step {steps} total_reward {total_reward:+0.2f}") print(f"step {steps} total_reward {total_reward:+0.2f}")
steps += 1 steps += 1
isopen = env.render() isopen = env.render()
if done or restart or isopen == False: if done or restart or isopen is False:
break break
env.close() env.close()

View File

@@ -1,7 +1,6 @@
__credits__ = ["Andrea PIERRÉ"] __credits__ = ["Andrea PIERRÉ"]
import math import math
import sys
from typing import Optional from typing import Optional
import Box2D import Box2D
@@ -17,7 +16,7 @@ from Box2D.b2 import (
import gym import gym
from gym import error, spaces from gym import error, spaces
from gym.utils import EzPickle, seeding from gym.utils import EzPickle
FPS = 50 FPS = 50
SCALE = 30.0 # affects how fast-paced the game is, forces should be adjusted as well 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: if render:
still_open = env.render() still_open = env.render()
if still_open == False: if still_open is False:
break break
if steps % 20 == 0 or done: if steps % 20 == 0 or done:

View File

@@ -5,7 +5,6 @@ import numpy as np
from numpy import cos, pi, sin from numpy import cos, pi, sin
from gym import core, spaces from gym import core, spaces
from gym.utils import seeding
__copyright__ = "Copyright 2013, RLPy http://acl.mit.edu/RLPy" __copyright__ = "Copyright 2013, RLPy http://acl.mit.edu/RLPy"
__credits__ = [ __credits__ = [

View File

@@ -10,7 +10,6 @@ import numpy as np
import gym import gym
from gym import logger, spaces from gym import logger, spaces
from gym.utils import seeding
class CartPoleEnv(gym.Env[np.ndarray, Union[int, np.ndarray]]): class CartPoleEnv(gym.Env[np.ndarray, Union[int, np.ndarray]]):

View File

@@ -20,7 +20,6 @@ import numpy as np
import gym import gym
from gym import spaces from gym import spaces
from gym.utils import seeding
class Continuous_MountainCarEnv(gym.Env): class Continuous_MountainCarEnv(gym.Env):

View File

@@ -9,7 +9,6 @@ import numpy as np
import gym import gym
from gym import spaces from gym import spaces
from gym.utils import seeding
class MountainCarEnv(gym.Env): class MountainCarEnv(gym.Env):

View File

@@ -7,7 +7,6 @@ import numpy as np
import gym import gym
from gym import spaces from gym import spaces
from gym.utils import seeding
class PendulumEnv(gym.Env): class PendulumEnv(gym.Env):

View File

@@ -7,7 +7,6 @@ import numpy as np
import gym import gym
from gym import error, spaces from gym import error, spaces
from gym.utils import seeding
try: try:
import mujoco_py import mujoco_py

View File

@@ -1,4 +1,3 @@
import mujoco_py
import numpy as np import numpy as np
from gym import utils from gym import utils

View File

@@ -7,6 +7,7 @@ import importlib
import importlib.util import importlib.util
import re import re
import sys import sys
import warnings
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import ( from typing import (
Any, Any,
@@ -225,6 +226,7 @@ def load_env_plugins(entry_point: str = "gym.envs") -> None:
for plugin in metadata.entry_points(group=entry_point): for plugin in metadata.entry_points(group=entry_point):
# Python 3.8 doesn't support plugin.module, plugin.attr # Python 3.8 doesn't support plugin.module, plugin.attr
# So we'll have to try and parse this ourselves # So we'll have to try and parse this ourselves
module, attr = None, None
try: try:
module, attr = plugin.module, plugin.attr # type: ignore ## error: Cannot access member "attr" for type "EntryPoint" module, attr = plugin.module, plugin.attr # type: ignore ## error: Cannot access member "attr" for type "EntryPoint"
except AttributeError: except AttributeError:
@@ -232,7 +234,10 @@ def load_env_plugins(entry_point: str = "gym.envs") -> None:
module, attr = plugin.value.split(":", maxsplit=1) module, attr = plugin.value.split(":", maxsplit=1)
else: else:
module, attr = plugin.value, None 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 module, attr = None, None
finally: finally:
if attr is None: if attr is None:
@@ -264,8 +269,12 @@ def load_env_plugins(entry_point: str = "gym.envs") -> None:
# fmt: off # fmt: off
# Classic control
# ----------------------------------------
@overload @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 @overload
def make(id: Literal["MountainCar-v0"], **kwargs) -> Env[np.ndarray, np.ndarray | int]: ... def make(id: Literal["MountainCar-v0"], **kwargs) -> Env[np.ndarray, np.ndarray | int]: ...
@overload @overload
@@ -278,6 +287,7 @@ def make(id: Literal["Acrobot-v1"], **kwargs) -> Env[np.ndarray, np.ndarray | in
# Box2d # Box2d
# ---------------------------------------- # ----------------------------------------
@overload @overload
def make(id: Literal["LunarLander-v2", "LunarLanderContinuous-v2"], **kwargs) -> Env[np.ndarray, np.ndarray | int]: ... def make(id: Literal["LunarLander-v2", "LunarLanderContinuous-v2"], **kwargs) -> Env[np.ndarray, np.ndarray | int]: ...
@overload @overload
@@ -288,6 +298,7 @@ def make(id: Literal["CarRacing-v1", "CarRacingDomainRandomize-v1"], **kwargs) -
# Toy Text # Toy Text
# ---------------------------------------- # ----------------------------------------
@overload @overload
def make(id: Literal["Blackjack-v1"], **kwargs) -> Env[np.ndarray, np.ndarray | int]: ... def make(id: Literal["Blackjack-v1"], **kwargs) -> Env[np.ndarray, np.ndarray | int]: ...
@overload @overload
@@ -299,6 +310,8 @@ def make(id: Literal["Taxi-v3"], **kwargs) -> Env[np.ndarray, np.ndarray | int]:
# Mujoco # Mujoco
# ---------------------------------------- # ----------------------------------------
@overload @overload
def make(id: Literal[ def make(id: Literal[
"Reacher-v2", "Reacher-v2",

View File

@@ -5,7 +5,6 @@ import numpy as np
import gym import gym
from gym import spaces from gym import spaces
from gym.utils import seeding
def cmp(a, b): def cmp(a, b):

View File

@@ -242,7 +242,6 @@ class FrozenLakeEnv(Env):
def _render_gui(self, desc, mode): def _render_gui(self, desc, mode):
import pygame import pygame
from pygame.constants import SRCALPHA
if self.window_surface is None: if self.window_surface is None:
pygame.init() pygame.init()

View File

@@ -1,6 +1,3 @@
import sys
class Error(Exception): class Error(Exception):
pass pass
@@ -133,7 +130,7 @@ class APIError(Error):
if http_body and hasattr(http_body, "decode"): if http_body and hasattr(http_body, "decode"):
try: try:
http_body = http_body.decode("utf-8") http_body = http_body.decode("utf-8")
except: except Exception:
http_body = "<Could not decode body as utf-8.>" http_body = "<Could not decode body as utf-8.>"
self._message = message self._message = message

View File

@@ -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. # These submodules should not have any import-time dependencies.
# We want this since we use `utils` during our import-time sanity checks # We want this since we use `utils` during our import-time sanity checks
# that verify that our dependencies are actually present. # that verify that our dependencies are actually present.
from .colorize import colorize from gym.utils.colorize import colorize
from .ezpickle import EzPickle from gym.utils.ezpickle import EzPickle

View File

@@ -5,7 +5,6 @@ from numpy.typing import NDArray
from pygame import Surface from pygame import Surface
from pygame.event import Event from pygame.event import Event
import gym
from gym import Env, logger from gym import Env, logger
try: try:

View File

@@ -4,7 +4,6 @@ import struct
from typing import Any, List, Optional, Tuple, Union from typing import Any, List, Optional, Tuple, Union
import numpy as np import numpy as np
from numpy.random import Generator
from gym import error from gym import error
from gym.logger import deprecation from gym.logger import deprecation

View File

@@ -14,7 +14,6 @@ from gym.error import (
CustomSpaceError, CustomSpaceError,
NoAsyncCallError, NoAsyncCallError,
) )
from gym.logger import warn
from gym.vector.utils import ( from gym.vector.utils import (
CloudpickleWrapper, CloudpickleWrapper,
clear_mpi_env_vars, clear_mpi_env_vars,
@@ -639,7 +638,7 @@ def _worker(index, env_fn, pipe, parent_pipe, shared_memory, error_queue):
while True: while True:
command, data = pipe.recv() command, data = pipe.recv()
if command == "reset": 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) observation, info = env.reset(**data)
pipe.send(((observation, info), True)) pipe.send(((observation, info), True))
else: else:
@@ -703,7 +702,7 @@ def _worker_shared_memory(index, env_fn, pipe, parent_pipe, shared_memory, error
while True: while True:
command, data = pipe.recv() command, data = pipe.recv()
if command == "reset": 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) observation, info = env.reset(**data)
write_to_shared_memory( write_to_shared_memory(
observation_space, index, observation, shared_memory observation_space, index, observation, shared_memory

View File

@@ -3,8 +3,6 @@ from typing import List, Optional, Union
import numpy as np 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.utils import concatenate, create_empty_array, iterate
from gym.vector.vector_env import VectorEnv from gym.vector.vector_env import VectorEnv
@@ -108,7 +106,7 @@ class SyncVectorEnv(VectorEnv):
kwargs["seed"] = single_seed kwargs["seed"] = single_seed
if options is not None: if options is not None:
kwargs["options"] = options kwargs["options"] = options
if return_info == True: if return_info is True:
kwargs["return_info"] = return_info kwargs["return_info"] = return_info
if not return_info: if not return_info:

View File

@@ -4,7 +4,6 @@ from functools import singledispatch
import numpy as np import numpy as np
from gym.spaces import Box, Dict, Discrete, MultiBinary, MultiDiscrete, Space, Tuple from gym.spaces import Box, Dict, Discrete, MultiBinary, MultiDiscrete, Space, Tuple
from gym.vector.utils.spaces import _BaseGymSpaces
__all__ = ["concatenate", "create_empty_array"] __all__ = ["concatenate", "create_empty_array"]

View File

@@ -5,10 +5,8 @@ from functools import singledispatch
import numpy as np import numpy as np
from gym import logger
from gym.error import CustomSpaceError from gym.error import CustomSpaceError
from gym.spaces import Box, Dict, Discrete, MultiBinary, MultiDiscrete, Space, Tuple from gym.spaces import Box, Dict, Discrete, MultiBinary, MultiDiscrete, Tuple
from gym.vector.utils.spaces import _BaseGymSpaces
__all__ = ["create_shared_memory", "read_from_shared_memory", "write_to_shared_memory"] __all__ = ["create_shared_memory", "read_from_shared_memory", "write_to_shared_memory"]

View File

@@ -1,8 +1,7 @@
from typing import List, Optional, Union from typing import List, Optional, Union
import gym import gym
from gym.logger import deprecation, warn from gym.logger import deprecation
from gym.spaces import Tuple
from gym.vector.utils.spaces import batch_space from gym.vector.utils.spaces import batch_space
__all__ = ["VectorEnv"] __all__ = ["VectorEnv"]

View File

@@ -1,4 +1,3 @@
from gym import error
from gym.wrappers.atari_preprocessing import AtariPreprocessing from gym.wrappers.atari_preprocessing import AtariPreprocessing
from gym.wrappers.autoreset import AutoResetWrapper from gym.wrappers.autoreset import AutoResetWrapper
from gym.wrappers.clip_action import ClipAction from gym.wrappers.clip_action import ClipAction

View File

@@ -1,5 +1,4 @@
from collections import deque from collections import deque
from typing import Optional
import numpy as np import numpy as np

View File

@@ -418,7 +418,7 @@ class ImageEncoder:
try: try:
self.proc.stdin.write(frame.tobytes()) self.proc.stdin.write(frame.tobytes())
except Exception as e: except Exception:
stdout, stderr = self.proc.communicate() stdout, stderr = self.proc.communicate()
logger.error("VideoRecorder encoder failed: %s", stderr) logger.error("VideoRecorder encoder failed: %s", stderr)

View File

@@ -1,5 +1,3 @@
from typing import Optional
import numpy as np import numpy as np
import gym import gym

View File

@@ -1,5 +1,3 @@
from typing import Optional
import gym import gym

View File

@@ -1,6 +1,5 @@
import time import time
from collections import deque from collections import deque
from typing import Optional
import numpy as np import numpy as np

View File

@@ -1,5 +1,5 @@
import os import os
from typing import Callable, Optional from typing import Callable
import gym import gym
from gym import logger from gym import logger

View File

@@ -1,5 +1,3 @@
from typing import Optional
import numpy as np import numpy as np
from gym import ObservationWrapper from gym import ObservationWrapper

View File

@@ -1,5 +1,3 @@
from typing import Optional
import gym import gym

View File

@@ -6,7 +6,7 @@ from setuptools import find_packages, setup
# Don't import gym module here, since deps may not be installed # Don't import gym module here, since deps may not be installed
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "gym")) 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. # Environment-specific dependencies.
extras = { extras = {

View File

@@ -11,7 +11,7 @@ SKIP_MUJOCO_WARNING_MESSAGE = (
skip_mujoco = not (os.environ.get("MUJOCO_KEY")) skip_mujoco = not (os.environ.get("MUJOCO_KEY"))
if not skip_mujoco: if not skip_mujoco:
try: try:
import mujoco_py import mujoco_py # noqa:F401
except ImportError: except ImportError:
skip_mujoco = True skip_mujoco = True
@@ -24,12 +24,12 @@ def should_skip_env_spec_for_tests(spec):
if skip_mujoco and ep.startswith("gym.envs.mujoco"): if skip_mujoco and ep.startswith("gym.envs.mujoco"):
return True return True
try: try:
import gym.envs.atari import gym.envs.atari # noqa:F401
except ImportError: except ImportError:
if ep.startswith("gym.envs.atari"): if ep.startswith("gym.envs.atari"):
return True return True
try: try:
import Box2D import Box2D # noqa:F401
except ImportError: except ImportError:
if ep.startswith("gym.envs.box2d"): if ep.startswith("gym.envs.box2d"):
return True return True

View File

@@ -1,5 +1,3 @@
import pickle
import pytest import pytest
from gym import envs from gym import envs

View File

@@ -1,11 +1,11 @@
import pytest
pytest.importorskip("gym.envs.atari")
from itertools import product from itertools import product
import pytest
from gym.envs.registration import registry from gym.envs.registration import registry
pytest.importorskip("gym.envs.atari")
def test_ale_legacy_env_specs(): def test_ale_legacy_env_specs():
versions = ["-v0", "-v4"] versions = ["-v0", "-v4"]

View File

@@ -61,7 +61,7 @@ def test_env(spec):
@pytest.mark.parametrize("spec", spec_list, ids=[spec.id for spec in spec_list]) @pytest.mark.parametrize("spec", spec_list, ids=[spec.id for spec in spec_list])
def test_reset_info(spec): def test_reset_info(spec):
with pytest.warns(None) as warnings: with pytest.warns(None):
env = spec.make() env = spec.make()
ob_space = env.observation_space ob_space = env.observation_space
@@ -78,13 +78,12 @@ def test_reset_info(spec):
# Run a longer rollout on some environments # Run a longer rollout on some environments
def test_random_rollout(): def test_random_rollout():
for env in [envs.make("CartPole-v1"), envs.make("FrozenLake-v1")]: for env in [envs.make("CartPole-v1"), envs.make("FrozenLake-v1")]:
agent = lambda ob: env.action_space.sample()
ob = env.reset() ob = env.reset()
for _ in range(10): for _ in range(10):
assert env.observation_space.contains(ob) assert env.observation_space.contains(ob)
a = agent(ob) action = env.action_space.sample()
assert env.action_space.contains(a) assert env.action_space.contains(action)
(ob, _reward, done, _info) = env.step(a) (ob, _reward, done, _info) = env.step(action)
if done: if done:
break break
env.close() env.close()

View File

@@ -1,6 +1,3 @@
import numpy as np
import pytest
from gym.envs.toy_text.frozen_lake import generate_random_map from gym.envs.toy_text.frozen_lake import generate_random_map

View File

@@ -2,9 +2,8 @@ import pytest
import gym import gym
from gym import envs, error 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.classic_control import cartpole
from gym.envs.registration import EnvSpec
class ArgumentEnv(gym.Env): class ArgumentEnv(gym.Env):

View File

@@ -569,20 +569,20 @@ def test_infinite_space(space):
# but floats are unbounded for infinite # but floats are unbounded for infinite
if np.any(space.high != 0): if np.any(space.high != 0):
assert ( assert (
space.is_bounded("above") == False space.is_bounded("above") is False
), "inf upper bound supposed to be unbounded" ), "inf upper bound supposed to be unbounded"
else: else:
assert ( assert (
space.is_bounded("above") == True space.is_bounded("above") is True
), "non-inf upper bound supposed to be bounded" ), "non-inf upper bound supposed to be bounded"
if np.any(space.low != 0): if np.any(space.low != 0):
assert ( assert (
space.is_bounded("below") == False space.is_bounded("below") is False
), "inf lower bound supposed to be unbounded" ), "inf lower bound supposed to be unbounded"
else: else:
assert ( assert (
space.is_bounded("below") == True space.is_bounded("below") is True
), "non-inf lower bound supposed to be bounded" ), "non-inf lower bound supposed to be bounded"
# check for dtype # check for dtype

View File

@@ -67,7 +67,7 @@ def test_play_relevant_keys_no_mapping():
env = DummyPlayEnv() env = DummyPlayEnv()
env.spec = DummyEnvSpec("DummyPlayEnv") env.spec = DummyEnvSpec("DummyPlayEnv")
with pytest.raises(MissingKeysToAction) as info: with pytest.raises(MissingKeysToAction):
PlayableGame(env) PlayableGame(env)
@@ -96,18 +96,18 @@ def test_keyboard_quit_event():
env = DummyPlayEnv() env = DummyPlayEnv()
game = PlayableGame(env, dummy_keys_to_action()) game = PlayableGame(env, dummy_keys_to_action())
event = Event(pygame.KEYDOWN, {"key": pygame.K_ESCAPE}) event = Event(pygame.KEYDOWN, {"key": pygame.K_ESCAPE})
assert game.running == True assert game.running is True
game.process_event(event) game.process_event(event)
assert game.running == False assert game.running is False
def test_pygame_quit_event(): def test_pygame_quit_event():
env = DummyPlayEnv() env = DummyPlayEnv()
game = PlayableGame(env, dummy_keys_to_action()) game = PlayableGame(env, dummy_keys_to_action())
event = Event(pygame.QUIT) event = Event(pygame.QUIT)
assert game.running == True assert game.running is True
game.process_event(event) game.process_event(event)
assert game.running == False assert game.running is False
def test_keyboard_relevant_keydown_event(): def test_keyboard_relevant_keydown_event():

View File

@@ -167,7 +167,7 @@ def test_reset_timeout_async_vector_env(shared_memory):
try: try:
env = AsyncVectorEnv(env_fns, shared_memory=shared_memory) env = AsyncVectorEnv(env_fns, shared_memory=shared_memory)
env.reset_async() env.reset_async()
observations = env.reset_wait(timeout=0.1) env.reset_wait(timeout=0.1)
finally: finally:
env.close(terminate=True) env.close(terminate=True)
@@ -178,7 +178,7 @@ def test_step_timeout_async_vector_env(shared_memory):
with pytest.raises(TimeoutError): with pytest.raises(TimeoutError):
try: try:
env = AsyncVectorEnv(env_fns, shared_memory=shared_memory) env = AsyncVectorEnv(env_fns, shared_memory=shared_memory)
observations = env.reset() env.reset()
env.step_async([0.1, 0.1, 0.3, 0.1]) env.step_async([0.1, 0.1, 0.3, 0.1])
observations, rewards, dones, _ = env.step_wait(timeout=0.1) observations, rewards, dones, _ = env.step_wait(timeout=0.1)
finally: finally:
@@ -192,7 +192,7 @@ def test_reset_out_of_order_async_vector_env(shared_memory):
with pytest.raises(NoAsyncCallError): with pytest.raises(NoAsyncCallError):
try: try:
env = AsyncVectorEnv(env_fns, shared_memory=shared_memory) env = AsyncVectorEnv(env_fns, shared_memory=shared_memory)
observations = env.reset_wait() env.reset_wait()
except NoAsyncCallError as exception: except NoAsyncCallError as exception:
assert exception.name == "reset" assert exception.name == "reset"
raise raise
@@ -203,7 +203,7 @@ def test_reset_out_of_order_async_vector_env(shared_memory):
try: try:
env = AsyncVectorEnv(env_fns, shared_memory=shared_memory) env = AsyncVectorEnv(env_fns, shared_memory=shared_memory)
actions = env.action_space.sample() actions = env.action_space.sample()
observations = env.reset() env.reset()
env.step_async(actions) env.step_async(actions)
env.reset_async() env.reset_async()
except NoAsyncCallError as exception: except NoAsyncCallError as exception:
@@ -248,7 +248,7 @@ def test_already_closed_async_vector_env(shared_memory):
with pytest.raises(ClosedEnvironmentError): with pytest.raises(ClosedEnvironmentError):
env = AsyncVectorEnv(env_fns, shared_memory=shared_memory) env = AsyncVectorEnv(env_fns, shared_memory=shared_memory)
env.close() env.close()
observations = env.reset() env.reset()
@pytest.mark.parametrize("shared_memory", [True, False]) @pytest.mark.parametrize("shared_memory", [True, False])

View File

@@ -65,8 +65,7 @@ def test_create_shared_memory(space, expected_type, n, ctx):
# Assert the length of the array # Assert the length of the array
assert len(lhs[:]) == n * len(rhs[:]) assert len(lhs[:]) == n * len(rhs[:])
# Assert the data type # Assert the data type
assert type(lhs[0]) == type(rhs[0]) # noqa: E721 assert isinstance(lhs[0], type(rhs[0]))
else: else:
raise TypeError(f"Got unknown type `{type(lhs)}`.") 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): def test_create_shared_memory_custom_space(n, ctx, space):
ctx = mp if (ctx is None) else mp.get_context(ctx) ctx = mp if (ctx is None) else mp.get_context(ctx)
with pytest.raises(CustomSpaceError): 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( @pytest.mark.parametrize(

View File

@@ -5,7 +5,7 @@ import pytest
from numpy.testing import assert_array_equal from numpy.testing import assert_array_equal
from gym import Space 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 gym.vector.utils.spaces import batch_space, iterate
from tests.vector.utils import CustomSpace, assert_rng_equal, custom_spaces, spaces from tests.vector.utils import CustomSpace, assert_rng_equal, custom_spaces, spaces

View File

@@ -1,4 +1,3 @@
import gym
from gym.vector import VectorEnvWrapper, make from gym.vector import VectorEnvWrapper, make

View File

@@ -5,7 +5,7 @@ import numpy as np
import pytest import pytest
import gym import gym
from gym.spaces import Box, Dict, Discrete, Tuple from gym.spaces import Box, Dict, Tuple
from gym.wrappers import FilterObservation, FlattenObservation from gym.wrappers import FilterObservation, FlattenObservation

View File

@@ -1,4 +1,3 @@
import types
from typing import Optional from typing import Optional
from unittest.mock import MagicMock from unittest.mock import MagicMock
@@ -23,7 +22,9 @@ class DummyResetEnv(gym.Env):
metadata = {} metadata = {}
def __init__(self): 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( self.observation_space = gym.spaces.Box(
low=np.array([-1.0]), high=np.array([1.0]) 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) obs, info = env.reset(return_info=True)
assert ob_space.contains(obs) assert ob_space.contains(obs)
assert isinstance(info, dict) assert isinstance(info, dict)
env.close()
@pytest.mark.parametrize("spec", spec_list, ids=[spec.id for spec in spec_list]) @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 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. amount of time with random actions, which is true as of the time of adding this test.
""" """
env = None with pytest.warns(None):
with pytest.warns(None) as warnings:
env = spec.make(autoreset=True) env = spec.make(autoreset=True)
ob_space = env.observation_space env.reset(seed=0)
obs = env.reset(seed=0)
env.action_space.seed(0) env.action_space.seed(0)
env.unwrapped.reset = MagicMock(side_effect=env.unwrapped.reset) env.unwrapped.reset = MagicMock(side_effect=env.unwrapped.reset)
@@ -90,22 +90,23 @@ def test_make_autoreset_true(spec):
assert isinstance(env, AutoResetWrapper) assert isinstance(env, AutoResetWrapper)
assert env.unwrapped.reset.called assert env.unwrapped.reset.called
env.close()
@pytest.mark.parametrize("spec", spec_list, ids=[spec.id for spec in spec_list]) @pytest.mark.parametrize("spec", spec_list, ids=[spec.id for spec in spec_list])
def test_make_autoreset_false(spec): def test_make_autoreset_false(spec):
env = None with pytest.warns(None):
with pytest.warns(None) as warnings:
env = spec.make(autoreset=False) env = spec.make(autoreset=False)
assert not isinstance(env, AutoResetWrapper) assert not isinstance(env, AutoResetWrapper)
env.close()
@pytest.mark.parametrize("spec", spec_list, ids=[spec.id for spec in spec_list]) @pytest.mark.parametrize("spec", spec_list, ids=[spec.id for spec in spec_list])
def test_make_autoreset_default_false(spec): def test_make_autoreset_default_false(spec):
env = None with pytest.warns(None):
with pytest.warns(None) as warnings:
env = spec.make() env = spec.make()
assert not isinstance(env, AutoResetWrapper) assert not isinstance(env, AutoResetWrapper)
env.close()
def test_autoreset_autoreset(): def test_autoreset_autoreset():
@@ -118,16 +119,16 @@ def test_autoreset_autoreset():
obs, reward, done, info = env.step(action) obs, reward, done, info = env.step(action)
assert obs == np.array([1]) assert obs == np.array([1])
assert reward == 0 assert reward == 0
assert done == False assert done is False
assert info == {"count": 1} assert info == {"count": 1}
obs, reward, done, info = env.step(action) obs, reward, done, info = env.step(action)
assert obs == np.array([2]) assert obs == np.array([2])
assert done == False assert done is False
assert reward == 0 assert reward == 0
assert info == {"count": 2} assert info == {"count": 2}
obs, reward, done, info = env.step(action) obs, reward, done, info = env.step(action)
assert obs == np.array([0]) assert obs == np.array([0])
assert done == True assert done is True
assert reward == 1 assert reward == 1
assert info == { assert info == {
"count": 0, "count": 0,
@@ -137,10 +138,11 @@ def test_autoreset_autoreset():
obs, reward, done, info = env.step(action) obs, reward, done, info = env.step(action)
assert obs == np.array([1]) assert obs == np.array([1])
assert reward == 0 assert reward == 0
assert done == False assert done is False
assert info == {"count": 1} assert info == {"count": 1}
obs, reward, done, info = env.step(action) obs, reward, done, info = env.step(action)
assert obs == np.array([2]) assert obs == np.array([2])
assert reward == 0 assert reward == 0
assert done == False assert done is False
assert info == {"count": 2} assert info == {"count": 2}
env.close()

View File

@@ -6,9 +6,8 @@ from gym.wrappers import ClipAction
def test_clip_action(): def test_clip_action():
# mountaincar: action-based rewards # mountaincar: action-based rewards
make_env = lambda: gym.make("MountainCarContinuous-v0") env = gym.make("MountainCarContinuous-v0")
env = make_env() wrapped_env = ClipAction(gym.make("MountainCarContinuous-v0"))
wrapped_env = ClipAction(make_env())
seed = 0 seed = 0

View File

@@ -1,8 +1,5 @@
import pytest
pytest.importorskip("gym.envs.atari")
import numpy as np import numpy as np
import pytest
import gym import gym
from gym.wrappers import FrameStack from gym.wrappers import FrameStack
@@ -13,6 +10,9 @@ except ImportError:
lz4 = None lz4 = None
pytest.importorskip("gym.envs.atari")
@pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v1", "Pong-v0"]) @pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v1", "Pong-v0"])
@pytest.mark.parametrize("num_stack", [2, 3, 4]) @pytest.mark.parametrize("num_stack", [2, 3, 4])
@pytest.mark.parametrize( @pytest.mark.parametrize(

View File

@@ -1,6 +1,3 @@
import numpy as np
import pytest
import gym import gym
from gym.wrappers import OrderEnforcing from gym.wrappers import OrderEnforcing

View File

@@ -1,4 +1,3 @@
import numpy as np
import pytest import pytest
import gym import gym

View File

@@ -1,15 +1,8 @@
import os import os
import shutil import shutil
import numpy as np
import pytest
import gym import gym
from gym.wrappers import ( from gym.wrappers import capped_cubic_video_schedule
RecordEpisodeStatistics,
RecordVideo,
capped_cubic_video_schedule,
)
def test_record_video_using_default_trigger(): def test_record_video_using_default_trigger():

View File

@@ -1,6 +1,3 @@
import numpy as np
import pytest
import gym import gym
from gym.wrappers import TimeLimit from gym.wrappers import TimeLimit

View File

@@ -7,7 +7,9 @@ from gym.wrappers import TransformObservation
@pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v1"]) @pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v1"])
def test_transform_observation(env_id): 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) env = gym.make(env_id)
wrapped_env = TransformObservation( wrapped_env = TransformObservation(
gym.make(env_id), lambda obs: affine_transform(obs) gym.make(env_id), lambda obs: affine_transform(obs)