The following issues were found

gym/envs/classic_control/mountain_car.py
18 issues
Attribute 'state' defined outside __init__
Error

Line: 98 Column: 9

                      done = bool(position >= self.goal_position and velocity >= self.goal_velocity)
        reward = -1.0

        self.state = (position, velocity)
        return np.array(self.state), reward, done, {}

    def reset(self):
        self.state = np.array([self.np_random.uniform(low=-0.6, high=-0.4), 0])
        return np.array(self.state)

            

Reported by Pylint.

Attribute 'state' defined outside __init__
Error

Line: 102 Column: 9

                      return np.array(self.state), reward, done, {}

    def reset(self):
        self.state = np.array([self.np_random.uniform(low=-0.6, high=-0.4), 0])
        return np.array(self.state)

    def _height(self, xs):
        return np.sin(3 * xs) * 0.45 + 0.55


            

Reported by Pylint.

Attribute 'track' defined outside __init__
Error

Line: 125 Column: 13

                          ys = self._height(xs)
            xys = list(zip((xs - self.min_position) * scale, ys * scale))

            self.track = rendering.make_polyline(xys)
            self.track.set_linewidth(4)
            self.viewer.add_geom(self.track)

            clearance = 10


            

Reported by Pylint.

Attribute 'cartrans' defined outside __init__
Error

Line: 134 Column: 13

                          l, r, t, b = -carwidth / 2, carwidth / 2, carheight, 0
            car = rendering.FilledPolygon([(l, b), (l, t), (r, t), (r, b)])
            car.add_attr(rendering.Transform(translation=(0, clearance)))
            self.cartrans = rendering.Transform()
            car.add_attr(self.cartrans)
            self.viewer.add_geom(car)
            frontwheel = rendering.make_circle(carheight / 2.5)
            frontwheel.set_color(0.5, 0.5, 0.5)
            frontwheel.add_attr(

            

Reported by Pylint.

Too many instance attributes (16/7)
Error

Line: 14 Column: 1

              from gym.utils import seeding


class MountainCarEnv(gym.Env):
    """
    Description:
        The agent (a car) is started at the bottom of a valley. For any given
        state the agent may choose to accelerate to the left, right or cease
        any acceleration.

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 82
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                      return [seed]

    def step(self, action):
        assert self.action_space.contains(action), "%r (%s) invalid" % (
            action,
            type(action),
        )

        position, velocity = self.state

            

Reported by Bandit.

Method could be a function
Error

Line: 105 Column: 5

                      self.state = np.array([self.np_random.uniform(low=-0.6, high=-0.4), 0])
        return np.array(self.state)

    def _height(self, xs):
        return np.sin(3 * xs) * 0.45 + 0.55

    def render(self, mode="human"):
        screen_width = 600
        screen_height = 400

            

Reported by Pylint.

Argument name "xs" doesn't conform to snake_case naming style
Error

Line: 105 Column: 5

                      self.state = np.array([self.np_random.uniform(low=-0.6, high=-0.4), 0])
        return np.array(self.state)

    def _height(self, xs):
        return np.sin(3 * xs) * 0.45 + 0.55

    def render(self, mode="human"):
        screen_width = 600
        screen_height = 400

            

Reported by Pylint.

Too many local variables (26/15)
Error

Line: 108 Column: 5

                  def _height(self, xs):
        return np.sin(3 * xs) * 0.45 + 0.55

    def render(self, mode="human"):
        screen_width = 600
        screen_height = 400

        world_width = self.max_position - self.min_position
        scale = screen_width / world_width

            

Reported by Pylint.

Import outside toplevel (gym.envs.classic_control.rendering)
Error

Line: 118 Column: 13

                      carheight = 20

        if self.viewer is None:
            from gym.envs.classic_control import rendering

            self.viewer = rendering.Viewer(screen_width, screen_height)
            xs = np.linspace(self.min_position, self.max_position, 100)
            ys = self._height(xs)
            xys = list(zip((xs - self.min_position) * scale, ys * scale))

            

Reported by Pylint.

gym/wrappers/test_record_episode_statistics.py
18 issues
Unable to import 'pytest'
Error

Line: 1 Column: 1

              import pytest

import gym
from gym.wrappers import RecordEpisodeStatistics


@pytest.mark.parametrize("env_id", ["CartPole-v0", "Pendulum-v0"])
@pytest.mark.parametrize("deque_size", [2, 5])
def test_record_episode_statistics(env_id, deque_size):

            

Reported by Pylint.

Unused variable 'n'
Error

Line: 13 Column: 9

                  env = gym.make(env_id)
    env = RecordEpisodeStatistics(env, deque_size)

    for n in range(5):
        env.reset()
        assert env.episode_returns[0] == 0.0
        assert env.episode_lengths[0] == 0
        for t in range(env.spec.max_episode_steps):
            _, _, done, info = env.step(env.action_space.sample())

            

Reported by Pylint.

Unused variable 't'
Error

Line: 17 Column: 13

                      env.reset()
        assert env.episode_returns[0] == 0.0
        assert env.episode_lengths[0] == 0
        for t in range(env.spec.max_episode_steps):
            _, _, done, info = env.step(env.action_space.sample())
            if done:
                assert "episode" in info
                assert all([item in info["episode"] for item in ["r", "l", "t"]])
                break

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import pytest

import gym
from gym.wrappers import RecordEpisodeStatistics


@pytest.mark.parametrize("env_id", ["CartPole-v0", "Pendulum-v0"])
@pytest.mark.parametrize("deque_size", [2, 5])
def test_record_episode_statistics(env_id, deque_size):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 9 Column: 1

              
@pytest.mark.parametrize("env_id", ["CartPole-v0", "Pendulum-v0"])
@pytest.mark.parametrize("deque_size", [2, 5])
def test_record_episode_statistics(env_id, deque_size):
    env = gym.make(env_id)
    env = RecordEpisodeStatistics(env, deque_size)

    for n in range(5):
        env.reset()

            

Reported by Pylint.

Variable name "n" doesn't conform to snake_case naming style
Error

Line: 13 Column: 9

                  env = gym.make(env_id)
    env = RecordEpisodeStatistics(env, deque_size)

    for n in range(5):
        env.reset()
        assert env.episode_returns[0] == 0.0
        assert env.episode_lengths[0] == 0
        for t in range(env.spec.max_episode_steps):
            _, _, done, info = env.step(env.action_space.sample())

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 15
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

              
    for n in range(5):
        env.reset()
        assert env.episode_returns[0] == 0.0
        assert env.episode_lengths[0] == 0
        for t in range(env.spec.max_episode_steps):
            _, _, done, info = env.step(env.action_space.sample())
            if done:
                assert "episode" in info

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 16
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  for n in range(5):
        env.reset()
        assert env.episode_returns[0] == 0.0
        assert env.episode_lengths[0] == 0
        for t in range(env.spec.max_episode_steps):
            _, _, done, info = env.step(env.action_space.sample())
            if done:
                assert "episode" in info
                assert all([item in info["episode"] for item in ["r", "l", "t"]])

            

Reported by Bandit.

Variable name "t" doesn't conform to snake_case naming style
Error

Line: 17 Column: 13

                      env.reset()
        assert env.episode_returns[0] == 0.0
        assert env.episode_lengths[0] == 0
        for t in range(env.spec.max_episode_steps):
            _, _, done, info = env.step(env.action_space.sample())
            if done:
                assert "episode" in info
                assert all([item in info["episode"] for item in ["r", "l", "t"]])
                break

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 20
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                      for t in range(env.spec.max_episode_steps):
            _, _, done, info = env.step(env.action_space.sample())
            if done:
                assert "episode" in info
                assert all([item in info["episode"] for item in ["r", "l", "t"]])
                break
    assert len(env.return_queue) == deque_size
    assert len(env.length_queue) == deque_size


            

Reported by Bandit.

gym/spaces/box.py
18 issues
Attempted relative import beyond top-level package
Error

Line: 3 Column: 1

              import numpy as np

from .space import Space
from gym import logger


class Box(Space):
    """
    A (possibly unbounded) box in R^n. Specifically, a Box represents the

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np

from .space import Space
from gym import logger


class Box(Space):
    """
    A (possibly unbounded) box in R^n. Specifically, a Box represents the

            

Reported by Pylint.

third party import "from gym import logger" should be placed before "from .space import Space"
Error

Line: 4 Column: 1

              import numpy as np

from .space import Space
from gym import logger


class Box(Space):
    """
    A (possibly unbounded) box in R^n. Specifically, a Box represents the

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 26
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                  """

    def __init__(self, low, high, shape=None, dtype=np.float32):
        assert dtype is not None, "dtype must be explicitly provided. "
        self.dtype = np.dtype(dtype)

        # determine shape if it isn't provided directly
        if shape is not None:
            shape = tuple(shape)

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 32
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                      # determine shape if it isn't provided directly
        if shape is not None:
            shape = tuple(shape)
            assert (
                np.isscalar(low) or low.shape == shape
            ), "low.shape doesn't match provided shape"
            assert (
                np.isscalar(high) or high.shape == shape
            ), "high.shape doesn't match provided shape"

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 35
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                          assert (
                np.isscalar(low) or low.shape == shape
            ), "low.shape doesn't match provided shape"
            assert (
                np.isscalar(high) or high.shape == shape
            ), "high.shape doesn't match provided shape"
        elif not np.isscalar(low):
            shape = low.shape
            assert (

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 40
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                          ), "high.shape doesn't match provided shape"
        elif not np.isscalar(low):
            shape = low.shape
            assert (
                np.isscalar(high) or high.shape == shape
            ), "high.shape doesn't match low.shape"
        elif not np.isscalar(high):
            shape = high.shape
            assert (

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 45
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                          ), "high.shape doesn't match low.shape"
        elif not np.isscalar(high):
            shape = high.shape
            assert (
                np.isscalar(low) or low.shape == shape
            ), "low.shape doesn't match high.shape"
        else:
            raise ValueError(
                "shape must be provided or inferred from the shapes of low or high"

            

Reported by Bandit.

Unnecessary "else" after "return"
Error

Line: 64 Column: 13

                      self.high = high

        def _get_precision(dtype):
            if np.issubdtype(dtype, np.floating):
                return np.finfo(dtype).precision
            else:
                return np.inf

        low_precision = _get_precision(self.low.dtype)

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 83 Column: 9

                      self.bounded_below = -np.inf < self.low
        self.bounded_above = np.inf > self.high

        super(Box, self).__init__(self.shape, self.dtype)

    def is_bounded(self, manner="both"):
        below = np.all(self.bounded_below)
        above = np.all(self.bounded_above)
        if manner == "both":

            

Reported by Pylint.

gym/vector/tests/test_vector_env.py
18 issues
Unable to import 'pytest'
Error

Line: 1 Column: 1

              import pytest
import numpy as np

from gym.spaces import Tuple
from gym.vector.tests.utils import CustomSpace, make_env

from gym.vector.async_vector_env import AsyncVectorEnv
from gym.vector.sync_vector_env import SyncVectorEnv
from gym.vector.vector_env import VectorEnv

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import pytest
import numpy as np

from gym.spaces import Tuple
from gym.vector.tests.utils import CustomSpace, make_env

from gym.vector.async_vector_env import AsyncVectorEnv
from gym.vector.sync_vector_env import SyncVectorEnv
from gym.vector.vector_env import VectorEnv

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 13 Column: 1

              

@pytest.mark.parametrize("shared_memory", [True, False])
def test_vector_env_equal(shared_memory):
    env_fns = [make_env("CubeCrash-v0", i) for i in range(4)]
    num_steps = 100
    try:
        async_env = AsyncVectorEnv(env_fns, shared_memory=shared_memory)
        sync_env = SyncVectorEnv(env_fns)

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 23
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                      async_env.seed(0)
        sync_env.seed(0)

        assert async_env.num_envs == sync_env.num_envs
        assert async_env.observation_space == sync_env.observation_space
        assert async_env.single_observation_space == sync_env.single_observation_space
        assert async_env.action_space == sync_env.action_space
        assert async_env.single_action_space == sync_env.single_action_space


            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 24
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                      sync_env.seed(0)

        assert async_env.num_envs == sync_env.num_envs
        assert async_env.observation_space == sync_env.observation_space
        assert async_env.single_observation_space == sync_env.single_observation_space
        assert async_env.action_space == sync_env.action_space
        assert async_env.single_action_space == sync_env.single_action_space

        async_observations = async_env.reset()

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 25
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

              
        assert async_env.num_envs == sync_env.num_envs
        assert async_env.observation_space == sync_env.observation_space
        assert async_env.single_observation_space == sync_env.single_observation_space
        assert async_env.action_space == sync_env.action_space
        assert async_env.single_action_space == sync_env.single_action_space

        async_observations = async_env.reset()
        sync_observations = sync_env.reset()

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 26
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                      assert async_env.num_envs == sync_env.num_envs
        assert async_env.observation_space == sync_env.observation_space
        assert async_env.single_observation_space == sync_env.single_observation_space
        assert async_env.action_space == sync_env.action_space
        assert async_env.single_action_space == sync_env.single_action_space

        async_observations = async_env.reset()
        sync_observations = sync_env.reset()
        assert np.all(async_observations == sync_observations)

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 27
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                      assert async_env.observation_space == sync_env.observation_space
        assert async_env.single_observation_space == sync_env.single_observation_space
        assert async_env.action_space == sync_env.action_space
        assert async_env.single_action_space == sync_env.single_action_space

        async_observations = async_env.reset()
        sync_observations = sync_env.reset()
        assert np.all(async_observations == sync_observations)


            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 31
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

              
        async_observations = async_env.reset()
        sync_observations = sync_env.reset()
        assert np.all(async_observations == sync_observations)

        for _ in range(num_steps):
            actions = async_env.action_space.sample()
            assert actions in sync_env.action_space


            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 35
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

              
        for _ in range(num_steps):
            actions = async_env.action_space.sample()
            assert actions in sync_env.action_space

            async_observations, async_rewards, async_dones, _ = async_env.step(actions)
            sync_observations, sync_rewards, sync_dones, _ = sync_env.step(actions)

            assert np.all(async_observations == sync_observations)

            

Reported by Bandit.

gym/wrappers/atari_preprocessing.py
17 issues
Unused TimeLimit imported from gym.wrappers
Error

Line: 4 Column: 1

              import numpy as np
import gym
from gym.spaces import Box
from gym.wrappers import TimeLimit

try:
    import cv2
except ImportError:
    cv2 = None

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np
import gym
from gym.spaces import Box
from gym.wrappers import TimeLimit

try:
    import cv2
except ImportError:
    cv2 = None

            

Reported by Pylint.

Too many instance attributes (12/7)
Error

Line: 12 Column: 1

                  cv2 = None


class AtariPreprocessing(gym.Wrapper):
    r"""Atari 2600 preprocessings.

    This class follows the guidelines in
    Machado et al. (2018), "Revisiting the Arcade Learning Environment:
    Evaluation Protocols and Open Problems for General Agents".

            

Reported by Pylint.

Line too long (110/100)
Error

Line: 24 Column: 1

                  * NoopReset: obtain initial state by taking random number of no-ops on reset.
    * Frame skipping: 4 by default
    * Max-pooling: most recent two observations
    * Termination signal when a life is lost: turned off by default. Not recommended by Machado et al. (2018).
    * Resize to a square image: 84x84 by default
    * Grayscale observation: optional
    * Scale observation: optional

    Args:

            

Reported by Pylint.

Line too long (106/100)
Error

Line: 36 Column: 1

                      screen_size (int): resize Atari frame
        terminal_on_life_loss (bool): if True, then step() returns done=True whenever a
            life is lost.
        grayscale_obs (bool): if True, then gray scale observation is returned, otherwise, RGB observation
            is returned.
        grayscale_newaxis (bool): if True and grayscale_obs=True, then a channel axis is added to
            grayscale observations to make them 3-dimensional.
        scale_obs (bool): if True, then observation normalized in range [0,1] is returned. It also limits memory
            optimization benefits of FrameStack Wrapper.

            

Reported by Pylint.

Line too long (112/100)
Error

Line: 40 Column: 1

                          is returned.
        grayscale_newaxis (bool): if True and grayscale_obs=True, then a channel axis is added to
            grayscale observations to make them 3-dimensional.
        scale_obs (bool): if True, then observation normalized in range [0,1] is returned. It also limits memory
            optimization benefits of FrameStack Wrapper.
    """

    def __init__(
        self,

            

Reported by Pylint.

Too many arguments (9/5)
Error

Line: 44 Column: 5

                          optimization benefits of FrameStack Wrapper.
    """

    def __init__(
        self,
        env,
        noop_max=30,
        frame_skip=4,
        screen_size=84,

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 56
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                      scale_obs=False,
    ):
        super().__init__(env)
        assert (
            cv2 is not None
        ), "opencv-python package not installed! Try running pip install gym[atari] to get dependencies  for atari"
        assert frame_skip > 0
        assert screen_size > 0
        assert noop_max >= 0

            

Reported by Bandit.

Line too long (115/100)
Error

Line: 58 Column: 1

                      super().__init__(env)
        assert (
            cv2 is not None
        ), "opencv-python package not installed! Try running pip install gym[atari] to get dependencies  for atari"
        assert frame_skip > 0
        assert screen_size > 0
        assert noop_max >= 0
        if frame_skip > 1:
            assert "NoFrameskip" in env.spec.id, (

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 59
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                      assert (
            cv2 is not None
        ), "opencv-python package not installed! Try running pip install gym[atari] to get dependencies  for atari"
        assert frame_skip > 0
        assert screen_size > 0
        assert noop_max >= 0
        if frame_skip > 1:
            assert "NoFrameskip" in env.spec.id, (
                "disable frame-skipping in the original env. for more than one"

            

Reported by Bandit.

gym/wrappers/test_filter_observation.py
17 issues
Unable to import 'pytest'
Error

Line: 1 Column: 1

              import pytest
import numpy as np

import gym
from gym import spaces
from gym.wrappers.filter_observation import FilterObservation


class FakeEnvironment(gym.Env):

            

Reported by Pylint.

Parameters differ from overridden 'render' method
Error

Line: 19 Column: 5

                      )
        self.action_space = spaces.Box(shape=(1,), low=-1, high=1, dtype=np.float32)

    def render(self, width=32, height=32, *args, **kwargs):
        del args
        del kwargs
        image_shape = (height, width, 3)
        return np.zeros(image_shape, dtype=np.uint8)


            

Reported by Pylint.

Keyword argument before variable positional arguments list in the definition of render function
Error

Line: 19 Column: 5

                      )
        self.action_space = spaces.Box(shape=(1,), low=-1, high=1, dtype=np.float32)

    def render(self, width=32, height=32, *args, **kwargs):
        del args
        del kwargs
        image_shape = (height, width, 3)
        return np.zeros(image_shape, dtype=np.uint8)


            

Reported by Pylint.

Statement seems to have no effect
Error

Line: 81 Column: 9

                  ):
        env = FakeEnvironment(observation_keys=("key1", "key2"))

        ValueError

        with pytest.raises(error_type, match=error_match):
            FilterObservation(env, filter_keys=filter_keys)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import pytest
import numpy as np

import gym
from gym import spaces
from gym.wrappers.filter_observation import FilterObservation


class FakeEnvironment(gym.Env):

            

Reported by Pylint.

Missing class docstring
Error

Line: 9 Column: 1

              from gym.wrappers.filter_observation import FilterObservation


class FakeEnvironment(gym.Env):
    def __init__(self, observation_keys=("state")):
        self.observation_space = spaces.Dict(
            {
                name: spaces.Box(shape=(2,), low=-1, high=1, dtype=np.float32)
                for name in observation_keys

            

Reported by Pylint.

Missing class docstring
Error

Line: 50 Column: 1

              )


class TestFilterObservation(object):
    @pytest.mark.parametrize(
        "observation_keys,filter_keys", FILTER_OBSERVATION_TEST_CASES
    )
    def test_filter_observation(self, observation_keys, filter_keys):
        env = FakeEnvironment(observation_keys=observation_keys)

            

Reported by Pylint.

Class 'TestFilterObservation' inherits from object, can be safely removed from bases in python3
Error

Line: 50 Column: 1

              )


class TestFilterObservation(object):
    @pytest.mark.parametrize(
        "observation_keys,filter_keys", FILTER_OBSERVATION_TEST_CASES
    )
    def test_filter_observation(self, observation_keys, filter_keys):
        env = FakeEnvironment(observation_keys=observation_keys)

            

Reported by Pylint.

Method could be a function
Error

Line: 53 Column: 5

              class TestFilterObservation(object):
    @pytest.mark.parametrize(
        "observation_keys,filter_keys", FILTER_OBSERVATION_TEST_CASES
    )
    def test_filter_observation(self, observation_keys, filter_keys):
        env = FakeEnvironment(observation_keys=observation_keys)

        # Make sure we are testing the right environment for the test.
        observation_space = env.observation_space

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 53 Column: 5

              class TestFilterObservation(object):
    @pytest.mark.parametrize(
        "observation_keys,filter_keys", FILTER_OBSERVATION_TEST_CASES
    )
    def test_filter_observation(self, observation_keys, filter_keys):
        env = FakeEnvironment(observation_keys=observation_keys)

        # Make sure we are testing the right environment for the test.
        observation_space = env.observation_space

            

Reported by Pylint.

scripts/generate_json.py
17 issues
Unable to import 'gym'
Error

Line: 1 Column: 1

              from gym import envs, spaces, logger
import json
import os
import sys
import argparse

from gym.envs.tests.spec_list import should_skip_env_spec_for_tests
from gym.envs.tests.test_envs_semantics import generate_rollout_hash, hash_object


            

Reported by Pylint.

Unable to import 'gym.envs.tests.spec_list'
Error

Line: 7 Column: 1

              import sys
import argparse

from gym.envs.tests.spec_list import should_skip_env_spec_for_tests
from gym.envs.tests.test_envs_semantics import generate_rollout_hash, hash_object

DATA_DIR = os.path.join(os.path.dirname(__file__), os.pardir, "gym", "envs", "tests")
ROLLOUT_STEPS = 100
episodes = ROLLOUT_STEPS

            

Reported by Pylint.

Unable to import 'gym.envs.tests.test_envs_semantics'
Error

Line: 8 Column: 1

              import argparse

from gym.envs.tests.spec_list import should_skip_env_spec_for_tests
from gym.envs.tests.test_envs_semantics import generate_rollout_hash, hash_object

DATA_DIR = os.path.join(os.path.dirname(__file__), os.pardir, "gym", "envs", "tests")
ROLLOUT_STEPS = 100
episodes = ROLLOUT_STEPS
steps = ROLLOUT_STEPS

            

Reported by Pylint.

Unused spaces imported from gym
Error

Line: 1 Column: 1

              from gym import envs, spaces, logger
import json
import os
import sys
import argparse

from gym.envs.tests.spec_list import should_skip_env_spec_for_tests
from gym.envs.tests.test_envs_semantics import generate_rollout_hash, hash_object


            

Reported by Pylint.

Unused hash_object imported from gym.envs.tests.test_envs_semantics
Error

Line: 8 Column: 1

              import argparse

from gym.envs.tests.spec_list import should_skip_env_spec_for_tests
from gym.envs.tests.test_envs_semantics import generate_rollout_hash, hash_object

DATA_DIR = os.path.join(os.path.dirname(__file__), os.pardir, "gym", "envs", "tests")
ROLLOUT_STEPS = 100
episodes = ROLLOUT_STEPS
steps = ROLLOUT_STEPS

            

Reported by Pylint.

No exception type(s) specified
Error

Line: 50 Column: 5

                          rewards_hash,
            dones_hash,
        ) = generate_rollout_hash(spec)
    except:
        # If running the env generates an exception, don't write to the rollout file
        logger.warn(
            "Exception {} thrown while generating rollout for {}. Rollout not added.".format(
                sys.exc_info()[0], spec.id
            )

            

Reported by Pylint.

Redefining name 'outfile' from outer scope (line 21)
Error

Line: 98 Column: 41

              
    if modified:
        logger.info("Writing new rollout file to {}".format(ROLLOUT_FILE))
        with open(ROLLOUT_FILE, "w") as outfile:
            json.dump(rollout_dict, outfile, indent=2, sort_keys=True)
    else:
        logger.info("No modifications needed.")



            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from gym import envs, spaces, logger
import json
import os
import sys
import argparse

from gym.envs.tests.spec_list import should_skip_env_spec_for_tests
from gym.envs.tests.test_envs_semantics import generate_rollout_hash, hash_object


            

Reported by Pylint.

standard import "import json" should be placed before "from gym import envs, spaces, logger"
Error

Line: 2 Column: 1

              from gym import envs, spaces, logger
import json
import os
import sys
import argparse

from gym.envs.tests.spec_list import should_skip_env_spec_for_tests
from gym.envs.tests.test_envs_semantics import generate_rollout_hash, hash_object


            

Reported by Pylint.

standard import "import os" should be placed before "from gym import envs, spaces, logger"
Error

Line: 3 Column: 1

              from gym import envs, spaces, logger
import json
import os
import sys
import argparse

from gym.envs.tests.spec_list import should_skip_env_spec_for_tests
from gym.envs.tests.test_envs_semantics import generate_rollout_hash, hash_object


            

Reported by Pylint.

gym/envs/classic_control/continuous_mountain_car.py
16 issues
Attribute 'state' defined outside __init__
Error

Line: 121 Column: 9

                          reward = 100.0
        reward -= math.pow(action[0], 2) * 0.1

        self.state = np.array([position, velocity])
        return self.state, reward, done, {}

    def reset(self):
        self.state = np.array([self.np_random.uniform(low=-0.6, high=-0.4), 0])
        return np.array(self.state)

            

Reported by Pylint.

Attribute 'track' defined outside __init__
Error

Line: 148 Column: 13

                          ys = self._height(xs)
            xys = list(zip((xs - self.min_position) * scale, ys * scale))

            self.track = rendering.make_polyline(xys)
            self.track.set_linewidth(4)
            self.viewer.add_geom(self.track)

            clearance = 10


            

Reported by Pylint.

Attribute 'cartrans' defined outside __init__
Error

Line: 157 Column: 13

                          l, r, t, b = -carwidth / 2, carwidth / 2, carheight, 0
            car = rendering.FilledPolygon([(l, b), (l, t), (r, t), (r, b)])
            car.add_attr(rendering.Transform(translation=(0, clearance)))
            self.cartrans = rendering.Transform()
            car.add_attr(self.cartrans)
            self.viewer.add_geom(car)
            frontwheel = rendering.make_circle(carheight / 2.5)
            frontwheel.set_color(0.5, 0.5, 0.5)
            frontwheel.add_attr(

            

Reported by Pylint.

Class name "Continuous_MountainCarEnv" doesn't conform to PascalCase naming style
Error

Line: 26 Column: 1

              from gym.utils import seeding


class Continuous_MountainCarEnv(gym.Env):
    """
    Description:
        The agent (a car) is started at the bottom of a valley. For any given
        state the agent may choose to accelerate to the left, right or cease
        any acceleration.

            

Reported by Pylint.

Too many instance attributes (17/7)
Error

Line: 26 Column: 1

              from gym.utils import seeding


class Continuous_MountainCarEnv(gym.Env):
    """
    Description:
        The agent (a car) is started at the bottom of a valley. For any given
        state the agent may choose to accelerate to the left, right or cease
        any acceleration.

            

Reported by Pylint.

Line too long (105/100)
Error

Line: 44 Column: 1

                      Note: actual driving force is calculated by multipling the power coef by power (0.0015)

    Reward:
         Reward of 100 is awarded if the agent reached the flag (position = 0.45) on top of the mountain.
         Reward is decrease based on amount of energy consumed each step.

    Starting State:
         The position of the car is assigned a uniform random value in
         [-0.6 , -0.4].

            

Reported by Pylint.

Method could be a function
Error

Line: 128 Column: 5

                      self.state = np.array([self.np_random.uniform(low=-0.6, high=-0.4), 0])
        return np.array(self.state)

    def _height(self, xs):
        return np.sin(3 * xs) * 0.45 + 0.55

    def render(self, mode="human"):
        screen_width = 600
        screen_height = 400

            

Reported by Pylint.

Argument name "xs" doesn't conform to snake_case naming style
Error

Line: 128 Column: 5

                      self.state = np.array([self.np_random.uniform(low=-0.6, high=-0.4), 0])
        return np.array(self.state)

    def _height(self, xs):
        return np.sin(3 * xs) * 0.45 + 0.55

    def render(self, mode="human"):
        screen_width = 600
        screen_height = 400

            

Reported by Pylint.

Too many local variables (26/15)
Error

Line: 131 Column: 5

                  def _height(self, xs):
        return np.sin(3 * xs) * 0.45 + 0.55

    def render(self, mode="human"):
        screen_width = 600
        screen_height = 400

        world_width = self.max_position - self.min_position
        scale = screen_width / world_width

            

Reported by Pylint.

Import outside toplevel (gym.envs.classic_control.rendering)
Error

Line: 141 Column: 13

                      carheight = 20

        if self.viewer is None:
            from gym.envs.classic_control import rendering

            self.viewer = rendering.Viewer(screen_width, screen_height)
            xs = np.linspace(self.min_position, self.max_position, 100)
            ys = self._height(xs)
            xys = list(zip((xs - self.min_position) * scale, ys * scale))

            

Reported by Pylint.

gym/spaces/multi_discrete.py
16 issues
Attempted relative import beyond top-level package
Error

Line: 2 Column: 1

              import numpy as np
from .space import Space


class MultiDiscrete(Space):
    """
    - The multi-discrete action space consists of a series of discrete action spaces with different number of actions in each
    - It is useful to represent game controllers or keyboards where each key can be represented as a discrete action space
    - It is parametrized by passing an array of positive integers specifying number of actions for each discrete action space

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np
from .space import Space


class MultiDiscrete(Space):
    """
    - The multi-discrete action space consists of a series of discrete action spaces with different number of actions in each
    - It is useful to represent game controllers or keyboards where each key can be represented as a discrete action space
    - It is parametrized by passing an array of positive integers specifying number of actions for each discrete action space

            

Reported by Pylint.

Line too long (125/100)
Error

Line: 7 Column: 1

              
class MultiDiscrete(Space):
    """
    - The multi-discrete action space consists of a series of discrete action spaces with different number of actions in each
    - It is useful to represent game controllers or keyboards where each key can be represented as a discrete action space
    - It is parametrized by passing an array of positive integers specifying number of actions for each discrete action space

    Note: Some environment wrappers assume a value of 0 always represents the NOOP action.


            

Reported by Pylint.

Line too long (122/100)
Error

Line: 8 Column: 1

              class MultiDiscrete(Space):
    """
    - The multi-discrete action space consists of a series of discrete action spaces with different number of actions in each
    - It is useful to represent game controllers or keyboards where each key can be represented as a discrete action space
    - It is parametrized by passing an array of positive integers specifying number of actions for each discrete action space

    Note: Some environment wrappers assume a value of 0 always represents the NOOP action.

    e.g. Nintendo Game Controller

            

Reported by Pylint.

Line too long (125/100)
Error

Line: 9 Column: 1

                  """
    - The multi-discrete action space consists of a series of discrete action spaces with different number of actions in each
    - It is useful to represent game controllers or keyboards where each key can be represented as a discrete action space
    - It is parametrized by passing an array of positive integers specifying number of actions for each discrete action space

    Note: Some environment wrappers assume a value of 0 always represents the NOOP action.

    e.g. Nintendo Game Controller
    - Can be conceptualized as 3 discrete action spaces:

            

Reported by Pylint.

Line too long (105/100)
Error

Line: 16 Column: 1

                  e.g. Nintendo Game Controller
    - Can be conceptualized as 3 discrete action spaces:

        1) Arrow Keys: Discrete 5  - NOOP[0], UP[1], RIGHT[2], DOWN[3], LEFT[4]  - params: min: 0, max: 4
        2) Button A:   Discrete 2  - NOOP[0], Pressed[1] - params: min: 0, max: 1
        3) Button B:   Discrete 2  - NOOP[0], Pressed[1] - params: min: 0, max: 1

    - Can be initialized as


            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 31
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                      """
        nvec: vector of counts of each categorical variable
        """
        assert (np.array(nvec) > 0).all(), "nvec (counts) have to be positive"
        self.nvec = np.asarray(nvec, dtype=dtype)

        super(MultiDiscrete, self).__init__(self.nvec.shape, dtype)

    def sample(self):

            

Reported by Bandit.

Consider using Python 3 style super() without arguments
Error

Line: 34 Column: 9

                      assert (np.array(nvec) > 0).all(), "nvec (counts) have to be positive"
        self.nvec = np.asarray(nvec, dtype=dtype)

        super(MultiDiscrete, self).__init__(self.nvec.shape, dtype)

    def sample(self):
        return (self.np_random.random_sample(self.nvec.shape) * self.nvec).astype(
            self.dtype
        )

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 36 Column: 5

              
        super(MultiDiscrete, self).__init__(self.nvec.shape, dtype)

    def sample(self):
        return (self.np_random.random_sample(self.nvec.shape) * self.nvec).astype(
            self.dtype
        )

    def contains(self, x):

            

Reported by Pylint.

Argument name "x" doesn't conform to snake_case naming style
Error

Line: 41 Column: 5

                          self.dtype
        )

    def contains(self, x):
        if isinstance(x, list):
            x = np.array(x)  # Promote list to array for contains check
        # if nvec is uint32 and space dtype is uint32, then 0 <= x < self.nvec guarantees that x
        # is within correct bounds for space dtype (even though x does not have to be unsigned)
        return x.shape == self.shape and (0 <= x).all() and (x < self.nvec).all()

            

Reported by Pylint.

gym/envs/robotics/hand_env.py
16 issues
Unused import os
Error

Line: 1 Column: 1

              import os
import copy
import numpy as np

import gym
from gym import error, spaces
from gym.utils import seeding
from gym.envs.robotics import robot_env


            

Reported by Pylint.

Unused import copy
Error

Line: 2 Column: 1

              import os
import copy
import numpy as np

import gym
from gym import error, spaces
from gym.utils import seeding
from gym.envs.robotics import robot_env


            

Reported by Pylint.

Unused import gym
Error

Line: 5 Column: 1

              import copy
import numpy as np

import gym
from gym import error, spaces
from gym.utils import seeding
from gym.envs.robotics import robot_env



            

Reported by Pylint.

Unused spaces imported from gym
Error

Line: 6 Column: 1

              import numpy as np

import gym
from gym import error, spaces
from gym.utils import seeding
from gym.envs.robotics import robot_env


class HandEnv(robot_env.RobotEnv):

            

Reported by Pylint.

Unused error imported from gym
Error

Line: 6 Column: 1

              import numpy as np

import gym
from gym import error, spaces
from gym.utils import seeding
from gym.envs.robotics import robot_env


class HandEnv(robot_env.RobotEnv):

            

Reported by Pylint.

Unused seeding imported from gym.utils
Error

Line: 7 Column: 1

              
import gym
from gym import error, spaces
from gym.utils import seeding
from gym.envs.robotics import robot_env


class HandEnv(robot_env.RobotEnv):
    def __init__(self, model_path, n_substeps, initial_qpos, relative_control):

            

Reported by Pylint.

Method 'compute_reward' is abstract in class 'GoalEnv' but is not overridden
Error

Line: 11 Column: 1

              from gym.envs.robotics import robot_env


class HandEnv(robot_env.RobotEnv):
    def __init__(self, model_path, n_substeps, initial_qpos, relative_control):
        self.relative_control = relative_control

        super(HandEnv, self).__init__(
            model_path=model_path,

            

Reported by Pylint.

Method '_get_obs' is abstract in class 'RobotEnv' but is not overridden
Error

Line: 11 Column: 1

              from gym.envs.robotics import robot_env


class HandEnv(robot_env.RobotEnv):
    def __init__(self, model_path, n_substeps, initial_qpos, relative_control):
        self.relative_control = relative_control

        super(HandEnv, self).__init__(
            model_path=model_path,

            

Reported by Pylint.

Method '_is_success' is abstract in class 'RobotEnv' but is not overridden
Error

Line: 11 Column: 1

              from gym.envs.robotics import robot_env


class HandEnv(robot_env.RobotEnv):
    def __init__(self, model_path, n_substeps, initial_qpos, relative_control):
        self.relative_control = relative_control

        super(HandEnv, self).__init__(
            model_path=model_path,

            

Reported by Pylint.

Method '_sample_goal' is abstract in class 'RobotEnv' but is not overridden
Error

Line: 11 Column: 1

              from gym.envs.robotics import robot_env


class HandEnv(robot_env.RobotEnv):
    def __init__(self, model_path, n_substeps, initial_qpos, relative_control):
        self.relative_control = relative_control

        super(HandEnv, self).__init__(
            model_path=model_path,

            

Reported by Pylint.