The following issues were found

gym/envs/mujoco/mujoco_env.py
23 issues
Unnecessary pass statement
Error

Line: 108 Column: 9

                      Optionally implement this method, if you need to tinker with camera position
        and so forth.
        """
        pass

    # -----------------------------

    def reset(self):
        self.sim.reset()

            

Reported by Pylint.

Parameters differ from overridden 'render' method
Error

Line: 135 Column: 5

                      for _ in range(n_frames):
            self.sim.step()

    def render(
        self,
        mode="human",
        width=DEFAULT_SIZE,
        height=DEFAULT_SIZE,
        camera_id=None,

            

Reported by Pylint.

Access to a protected member _camera_name2id of a client class
Error

Line: 154 Column: 53

                          if no_camera_specified:
                camera_name = "track"

            if camera_id is None and camera_name in self.model._camera_name2id:
                camera_id = self.model.camera_name2id(camera_name)

            self._get_viewer(mode).render(width, height, camera_id=camera_id)

        if mode == "rgb_array":

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from collections import OrderedDict
import os


from gym import error, spaces
from gym.utils import seeding
import numpy as np
from os import path
import gym

            

Reported by Pylint.

standard import "from os import path" should be placed before "from gym import error, spaces"
Error

Line: 8 Column: 1

              from gym import error, spaces
from gym.utils import seeding
import numpy as np
from os import path
import gym

try:
    import mujoco_py
except ImportError as e:

            

Reported by Pylint.

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

Line: 13 Column: 1

              
try:
    import mujoco_py
except ImportError as e:
    raise error.DependencyNotInstalled(
        "{}. (HINT: you need to install mujoco_py, and also perform the setup instructions here: https://github.com/openai/mujoco-py/.)".format(
            e
        )
    )

            

Reported by Pylint.

Line too long (144/100)
Error

Line: 15 Column: 1

                  import mujoco_py
except ImportError as e:
    raise error.DependencyNotInstalled(
        "{}. (HINT: you need to install mujoco_py, and also perform the setup instructions here: https://github.com/openai/mujoco-py/.)".format(
            e
        )
    )

DEFAULT_SIZE = 500

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 23 Column: 1

              DEFAULT_SIZE = 500


def convert_observation_to_space(observation):
    if isinstance(observation, dict):
        space = spaces.Dict(
            OrderedDict(
                [
                    (key, convert_observation_to_space(value))

            

Reported by Pylint.

Too many instance attributes (12/7)
Error

Line: 43 Column: 1

                  return space


class MujocoEnv(gym.Env):
    """Superclass for all MuJoCo environments."""

    def __init__(self, model_path, frame_skip):
        if model_path.startswith("/"):
            fullpath = model_path

            

Reported by Pylint.

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

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

              
        action = self.action_space.sample()
        observation, _reward, done, _info = self.step(action)
        assert not done

        self._set_observation_space(observation)

        self.seed()


            

Reported by Bandit.

gym/utils/play.py
22 issues
Unable to import 'pygame'
Error

Line: 2 Column: 1

              import gym
import pygame
import matplotlib
import argparse
from gym import logger

try:
    matplotlib.use("TkAgg")
    import matplotlib.pyplot as plt

            

Reported by Pylint.

Unable to import 'pygame.locals'
Error

Line: 15 Column: 1

                  plt = None

from collections import deque
from pygame.locals import VIDEORESIZE


def display_arr(screen, arr, video_size, transpose):
    arr_min, arr_max = arr.min(), arr.max()
    arr = 255.0 * (arr - arr_min) / (arr_max - arr_min)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import gym
import pygame
import matplotlib
import argparse
from gym import logger

try:
    matplotlib.use("TkAgg")
    import matplotlib.pyplot as plt

            

Reported by Pylint.

standard import "import argparse" should be placed before "import gym"
Error

Line: 4 Column: 1

              import gym
import pygame
import matplotlib
import argparse
from gym import logger

try:
    matplotlib.use("TkAgg")
    import matplotlib.pyplot as plt

            

Reported by Pylint.

Imports from package matplotlib are not grouped
Error

Line: 9 Column: 5

              
try:
    matplotlib.use("TkAgg")
    import matplotlib.pyplot as plt
except ImportError as e:
    logger.warn("failed to set matplotlib backend, plotting will not work: %s" % str(e))
    plt = None

from collections import deque

            

Reported by Pylint.

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

Line: 10 Column: 1

              try:
    matplotlib.use("TkAgg")
    import matplotlib.pyplot as plt
except ImportError as e:
    logger.warn("failed to set matplotlib backend, plotting will not work: %s" % str(e))
    plt = None

from collections import deque
from pygame.locals import VIDEORESIZE

            

Reported by Pylint.

standard import "from collections import deque" should be placed before "import gym"
Error

Line: 14 Column: 1

                  logger.warn("failed to set matplotlib backend, plotting will not work: %s" % str(e))
    plt = None

from collections import deque
from pygame.locals import VIDEORESIZE


def display_arr(screen, arr, video_size, transpose):
    arr_min, arr_max = arr.min(), arr.max()

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 18 Column: 1

              from pygame.locals import VIDEORESIZE


def display_arr(screen, arr, video_size, transpose):
    arr_min, arr_max = arr.min(), arr.max()
    arr = 255.0 * (arr - arr_min) / (arr_max - arr_min)
    pyg_img = pygame.surfarray.make_surface(arr.swapaxes(0, 1) if transpose else arr)
    pyg_img = pygame.transform.scale(pyg_img, video_size)
    screen.blit(pyg_img, (0, 0))

            

Reported by Pylint.

Too many local variables (20/15)
Error

Line: 26 Column: 1

                  screen.blit(pyg_img, (0, 0))


def play(env, transpose=True, fps=30, zoom=None, callback=None, keys_to_action=None):
    """Allows one to play the game using keyboard.

    To simply play the game use:

        play(gym.make("Pong-v4"))

            

Reported by Pylint.

Too many branches (18/12)
Error

Line: 26 Column: 1

                  screen.blit(pyg_img, (0, 0))


def play(env, transpose=True, fps=30, zoom=None, callback=None, keys_to_action=None):
    """Allows one to play the game using keyboard.

    To simply play the game use:

        play(gym.make("Pong-v4"))

            

Reported by Pylint.

gym/core.py
22 issues
Unused closer imported from gym.utils
Error

Line: 5 Column: 1

              
import gym
from gym import error
from gym.utils import closer


class Env(object):
    """The main OpenAI Gym class. It encapsulates an environment with
    arbitrary behind-the-scenes dynamics. An environment can be

            

Reported by Pylint.

Unnecessary pass statement
Error

Line: 122 Column: 9

                      Environments will automatically close() themselves when
        garbage collected or when the program exits.
        """
        pass

    def seed(self, seed=None):
        """Sets the seed for this env's random number generator(s).

        Note:

            

Reported by Pylint.

Unused argument 'seed'
Error

Line: 124 Column: 20

                      """
        pass

    def seed(self, seed=None):
        """Sets the seed for this env's random number generator(s).

        Note:
            Some environments use multiple pseudorandom number generators.
            We want to capture all such seeds used in order to ensure that

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from abc import abstractmethod

import gym
from gym import error
from gym.utils import closer


class Env(object):
    """The main OpenAI Gym class. It encapsulates an environment with

            

Reported by Pylint.

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

Line: 8 Column: 1

              from gym.utils import closer


class Env(object):
    """The main OpenAI Gym class. It encapsulates an environment with
    arbitrary behind-the-scenes dynamics. An environment can be
    partially or fully observed.

    The main API methods that users of this class need to know are:

            

Reported by Pylint.

Line too long (104/100)
Error

Line: 27 Column: 1

                      observation_space: The Space object corresponding to valid observations
        reward_range: A tuple corresponding to the min and max possible rewards

    Note: a default reward range set to [-inf,+inf] already exists. Set it if you want a narrower range.

    The methods are accessed publicly as "step", "reset", etc...
    """

    # Set this in SOME subclasses

            

Reported by Pylint.

Line too long (120/100)
Error

Line: 55 Column: 1

                      Returns:
            observation (object): agent's observation of the current environment
            reward (float) : amount of reward returned after previous action
            done (bool): whether the episode has ended, in which case further step() calls will return undefined results
            info (dict): contains auxiliary diagnostic information (helpful for debugging, and sometimes learning)
        """
        raise NotImplementedError

    @abstractmethod

            

Reported by Pylint.

Line too long (114/100)
Error

Line: 56 Column: 1

                          observation (object): agent's observation of the current environment
            reward (float) : amount of reward returned after previous action
            done (bool): whether the episode has ended, in which case further step() calls will return undefined results
            info (dict): contains auxiliary diagnostic information (helpful for debugging, and sometimes learning)
        """
        raise NotImplementedError

    @abstractmethod
    def reset(self):

            

Reported by Pylint.

Method could be a function
Error

Line: 124 Column: 5

                      """
        pass

    def seed(self, seed=None):
        """Sets the seed for this env's random number generator(s).

        Note:
            Some environments use multiple pseudorandom number generators.
            We want to capture all such seeds used in order to ensure that

            

Reported by Pylint.

Unnecessary "else" after "return"
Error

Line: 151 Column: 9

                      return self

    def __str__(self):
        if self.spec is None:
            return "<{} instance>".format(type(self).__name__)
        else:
            return "<{}<{}>>".format(type(self).__name__, self.spec.id)

    def __enter__(self):

            

Reported by Pylint.

gym/envs/atari/atari_env.py
21 issues
Parameters differ from overridden 'step' method
Error

Line: 125 Column: 5

              
        return [seed1, seed2]

    def step(self, a):
        reward = 0.0
        action = self._action_set[a]

        if isinstance(self.frameskip, int):
            num_steps = self.frameskip

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np
import os
import gym
from gym import error, spaces
from gym import utils
from gym.utils import seeding

try:
    import atari_py

            

Reported by Pylint.

standard import "import os" should be placed before "import numpy as np"
Error

Line: 2 Column: 1

              import numpy as np
import os
import gym
from gym import error, spaces
from gym import utils
from gym.utils import seeding

try:
    import atari_py

            

Reported by Pylint.

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

Line: 10 Column: 1

              
try:
    import atari_py
except ImportError as e:
    raise error.DependencyNotInstalled(
        "{}. (HINT: you can install Atari dependencies by running "
        "'pip install gym[atari]'.)".format(e)
    )


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 17 Column: 1

                  )


def to_ram(ale):
    ram_size = ale.getRAMSize()
    ram = np.zeros((ram_size), dtype=np.uint8)
    ale.getRAM(ram)
    return ram


            

Reported by Pylint.

Missing class docstring
Error

Line: 24 Column: 1

                  return ram


class AtariEnv(gym.Env, utils.EzPickle):
    metadata = {"render.modes": ["human", "rgb_array"]}

    def __init__(
        self,
        game="pong",

            

Reported by Pylint.

Too many instance attributes (12/7)
Error

Line: 24 Column: 1

                  return ram


class AtariEnv(gym.Env, utils.EzPickle):
    metadata = {"render.modes": ["human", "rgb_array"]}

    def __init__(
        self,
        game="pong",

            

Reported by Pylint.

Too many arguments (8/5)
Error

Line: 27 Column: 5

              class AtariEnv(gym.Env, utils.EzPickle):
    metadata = {"render.modes": ["human", "rgb_array"]}

    def __init__(
        self,
        game="pong",
        mode=None,
        difficulty=None,
        obs_type="ram",

            

Reported by Pylint.

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

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

                          repeat_action_probability,
            full_action_space,
        )
        assert obs_type in ("ram", "image")

        self.game = game
        self.game_path = atari_py.get_game_path(game)
        self.game_mode = mode
        self.game_difficulty = difficulty

            

Reported by Bandit.

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

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

              
        # Tune (or disable) ALE's action repeat:
        # https://github.com/openai/gym/issues/349
        assert isinstance(
            repeat_action_probability, (float, int)
        ), "Invalid repeat_action_probability: {!r}".format(repeat_action_probability)
        self.ale.setFloat(
            "repeat_action_probability".encode("utf-8"), repeat_action_probability
        )

            

Reported by Bandit.

gym/envs/tests/test_determinism.py
21 issues
Unable to import 'pytest'
Error

Line: 2 Column: 1

              import numpy as np
import pytest

from gym.envs.tests.spec_list import spec_list


@pytest.mark.parametrize("spec", spec_list)
def test_env(spec):
    # Note that this precludes running this test in multiple

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np
import pytest

from gym.envs.tests.spec_list import spec_list


@pytest.mark.parametrize("spec", spec_list)
def test_env(spec):
    # Note that this precludes running this test in multiple

            

Reported by Pylint.

Too many local variables (20/15)
Error

Line: 8 Column: 1

              

@pytest.mark.parametrize("spec", spec_list)
def test_env(spec):
    # Note that this precludes running this test in multiple
    # threads. However, we probably already can't do multithreading
    # due to some environments.
    env1 = spec.make()
    env1.seed(0)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 8 Column: 1

              

@pytest.mark.parametrize("spec", spec_list)
def test_env(spec):
    # Note that this precludes running this test in multiple
    # threads. However, we probably already can't do multithreading
    # due to some environments.
    env1 = spec.make()
    env1.seed(0)

            

Reported by Pylint.

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

Line: 52 Column: 44

              
    assert_equals(initial_observation1, initial_observation2)

    for i, ((o1, r1, d1, i1), (o2, r2, d2, i2)) in enumerate(
        zip(step_responses1, step_responses2)
    ):
        assert_equals(o1, o2, "[{}] ".format(i))
        assert r1 == r2, "[{}] r1: {}, r2: {}".format(i, r1, r2)
        assert d1 == d2, "[{}] d1: {}, d2: {}".format(i, d1, d2)

            

Reported by Pylint.

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

Line: 52 Column: 14

              
    assert_equals(initial_observation1, initial_observation2)

    for i, ((o1, r1, d1, i1), (o2, r2, d2, i2)) in enumerate(
        zip(step_responses1, step_responses2)
    ):
        assert_equals(o1, o2, "[{}] ".format(i))
        assert r1 == r2, "[{}] r1: {}, r2: {}".format(i, r1, r2)
        assert d1 == d2, "[{}] d1: {}, d2: {}".format(i, d1, d2)

            

Reported by Pylint.

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

Line: 52 Column: 18

              
    assert_equals(initial_observation1, initial_observation2)

    for i, ((o1, r1, d1, i1), (o2, r2, d2, i2)) in enumerate(
        zip(step_responses1, step_responses2)
    ):
        assert_equals(o1, o2, "[{}] ".format(i))
        assert r1 == r2, "[{}] r1: {}, r2: {}".format(i, r1, r2)
        assert d1 == d2, "[{}] d1: {}, d2: {}".format(i, d1, d2)

            

Reported by Pylint.

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

Line: 52 Column: 22

              
    assert_equals(initial_observation1, initial_observation2)

    for i, ((o1, r1, d1, i1), (o2, r2, d2, i2)) in enumerate(
        zip(step_responses1, step_responses2)
    ):
        assert_equals(o1, o2, "[{}] ".format(i))
        assert r1 == r2, "[{}] r1: {}, r2: {}".format(i, r1, r2)
        assert d1 == d2, "[{}] d1: {}, d2: {}".format(i, d1, d2)

            

Reported by Pylint.

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

Line: 52 Column: 26

              
    assert_equals(initial_observation1, initial_observation2)

    for i, ((o1, r1, d1, i1), (o2, r2, d2, i2)) in enumerate(
        zip(step_responses1, step_responses2)
    ):
        assert_equals(o1, o2, "[{}] ".format(i))
        assert r1 == r2, "[{}] r1: {}, r2: {}".format(i, r1, r2)
        assert d1 == d2, "[{}] d1: {}, d2: {}".format(i, d1, d2)

            

Reported by Pylint.

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

Line: 52 Column: 32

              
    assert_equals(initial_observation1, initial_observation2)

    for i, ((o1, r1, d1, i1), (o2, r2, d2, i2)) in enumerate(
        zip(step_responses1, step_responses2)
    ):
        assert_equals(o1, o2, "[{}] ".format(i))
        assert r1 == r2, "[{}] r1: {}, r2: {}".format(i, r1, r2)
        assert d1 == d2, "[{}] d1: {}, d2: {}".format(i, d1, d2)

            

Reported by Pylint.

gym/spaces/tests/test_spaces.py
20 issues
Unable to import 'pytest'
Error

Line: 5 Column: 1

              from copy import copy

import numpy as np
import pytest

from gym.spaces import Tuple, Box, Discrete, MultiDiscrete, MultiBinary, Dict


@pytest.mark.parametrize(

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import json  # note: ujson fails this test due to float equality
from copy import copy

import numpy as np
import pytest

from gym.spaces import Tuple, Box, Discrete, MultiDiscrete, MultiBinary, Dict



            

Reported by Pylint.

Missing function or method docstring
Error

Line: 30 Column: 1

                              "position": Discrete(5),
                "velocity": Box(
                    low=np.array([0, 0]), high=np.array([1, 5]), dtype=np.float32
                ),
            }
        ),
    ],
)
def test_roundtripping(space):

            

Reported by Pylint.

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

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

              def test_roundtripping(space):
    sample_1 = space.sample()
    sample_2 = space.sample()
    assert space.contains(sample_1)
    assert space.contains(sample_2)
    json_rep = space.to_jsonable([sample_1, sample_2])

    json_roundtripped = json.loads(json.dumps(json_rep))


            

Reported by Bandit.

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

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

                  sample_1 = space.sample()
    sample_2 = space.sample()
    assert space.contains(sample_1)
    assert space.contains(sample_2)
    json_rep = space.to_jsonable([sample_1, sample_2])

    json_roundtripped = json.loads(json.dumps(json_rep))

    samples_after_roundtrip = space.from_jsonable(json_roundtripped)

            

Reported by Bandit.

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

Line: 47 Column: 5

                  samples_after_roundtrip = space.from_jsonable(json_roundtripped)
    sample_1_prime, sample_2_prime = samples_after_roundtrip

    s1 = space.to_jsonable([sample_1])
    s1p = space.to_jsonable([sample_1_prime])
    s2 = space.to_jsonable([sample_2])
    s2p = space.to_jsonable([sample_2_prime])
    assert s1 == s1p, "Expected {} to equal {}".format(s1, s1p)
    assert s2 == s2p, "Expected {} to equal {}".format(s2, s2p)

            

Reported by Pylint.

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

Line: 49 Column: 5

              
    s1 = space.to_jsonable([sample_1])
    s1p = space.to_jsonable([sample_1_prime])
    s2 = space.to_jsonable([sample_2])
    s2p = space.to_jsonable([sample_2_prime])
    assert s1 == s1p, "Expected {} to equal {}".format(s1, s1p)
    assert s2 == s2p, "Expected {} to equal {}".format(s2, s2p)



            

Reported by Pylint.

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

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

                  s1p = space.to_jsonable([sample_1_prime])
    s2 = space.to_jsonable([sample_2])
    s2p = space.to_jsonable([sample_2_prime])
    assert s1 == s1p, "Expected {} to equal {}".format(s1, s1p)
    assert s2 == s2p, "Expected {} to equal {}".format(s2, s2p)


@pytest.mark.parametrize(
    "space",

            

Reported by Bandit.

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

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

                  s2 = space.to_jsonable([sample_2])
    s2p = space.to_jsonable([sample_2_prime])
    assert s1 == s1p, "Expected {} to equal {}".format(s1, s1p)
    assert s2 == s2p, "Expected {} to equal {}".format(s2, s2p)


@pytest.mark.parametrize(
    "space",
    [

            

Reported by Bandit.

Missing function or method docstring
Error

Line: 76 Column: 1

                              "position": Discrete(5),
                "velocity": Box(
                    low=np.array([0, 0]), high=np.array([1, 5]), dtype=np.float32
                ),
            }
        ),
    ],
)
def test_equality(space):

            

Reported by Pylint.

gym/envs/toy_text/taxi.py
20 issues
Missing module docstring
Error

Line: 1 Column: 1

              import sys
from contextlib import closing
from io import StringIO
from gym import utils
from gym.envs.toy_text import discrete
import numpy as np

MAP = [
    "+---------+",

            

Reported by Pylint.

Line too long (456/100)
Error

Line: 26 Column: 1

                  by Tom Dietterich

    Description:
    There are four designated locations in the grid world indicated by R(ed), G(reen), Y(ellow), and B(lue). When the episode starts, the taxi starts off at a random square and the passenger is at a random location. The taxi drives to the passenger's location, picks up the passenger, drives to the passenger's destination (another one of the four specified locations), and then drops off the passenger. Once the passenger is dropped off, the episode ends.

    Observations:
    There are 500 discrete states since there are 25 taxi positions, 5 possible locations of the passenger (including the case when the passenger is in the taxi), and 4 destination locations.

    Passenger locations:

            

Reported by Pylint.

Line too long (191/100)
Error

Line: 29 Column: 1

                  There are four designated locations in the grid world indicated by R(ed), G(reen), Y(ellow), and B(lue). When the episode starts, the taxi starts off at a random square and the passenger is at a random location. The taxi drives to the passenger's location, picks up the passenger, drives to the passenger's destination (another one of the four specified locations), and then drops off the passenger. Once the passenger is dropped off, the episode ends.

    Observations:
    There are 500 discrete states since there are 25 taxi positions, 5 possible locations of the passenger (including the case when the passenger is in the taxi), and 4 destination locations.

    Passenger locations:
    - 0: R(ed)
    - 1: G(reen)
    - 2: Y(ellow)

            

Reported by Pylint.

Too many branches (17/12)
Error

Line: 71 Column: 5

              
    metadata = {"render.modes": ["human", "ansi"]}

    def __init__(self):
        self.desc = np.asarray(MAP, dtype="c")

        self.locs = locs = [(0, 0), (0, 4), (4, 0), (4, 3)]

        num_states = 500

            

Reported by Pylint.

Too many local variables (23/15)
Error

Line: 71 Column: 5

              
    metadata = {"render.modes": ["human", "ansi"]}

    def __init__(self):
        self.desc = np.asarray(MAP, dtype="c")

        self.locs = locs = [(0, 0), (0, 4), (4, 0), (4, 3)]

        num_states = 500

            

Reported by Pylint.

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

Line: 83 Column: 9

                      max_col = num_columns - 1
        initial_state_distrib = np.zeros(num_states)
        num_actions = 6
        P = {
            state: {action: [] for action in range(num_actions)}
            for state in range(num_states)
        }
        for row in range(num_rows):
            for col in range(num_columns):

            

Reported by Pylint.

Too many nested blocks (7/5)
Error

Line: 87 Column: 9

                          state: {action: [] for action in range(num_actions)}
            for state in range(num_states)
        }
        for row in range(num_rows):
            for col in range(num_columns):
                for pass_idx in range(len(locs) + 1):  # +1 for being inside taxi
                    for dest_idx in range(len(locs)):
                        state = self.encode(row, col, pass_idx, dest_idx)
                        if pass_idx < 4 and pass_idx != dest_idx:

            

Reported by Pylint.

Too many nested blocks (7/5)
Error

Line: 87 Column: 9

                          state: {action: [] for action in range(num_actions)}
            for state in range(num_states)
        }
        for row in range(num_rows):
            for col in range(num_columns):
                for pass_idx in range(len(locs) + 1):  # +1 for being inside taxi
                    for dest_idx in range(len(locs)):
                        state = self.encode(row, col, pass_idx, dest_idx)
                        if pass_idx < 4 and pass_idx != dest_idx:

            

Reported by Pylint.

Consider using enumerate instead of iterating with range and len
Error

Line: 90 Column: 21

                      for row in range(num_rows):
            for col in range(num_columns):
                for pass_idx in range(len(locs) + 1):  # +1 for being inside taxi
                    for dest_idx in range(len(locs)):
                        state = self.encode(row, col, pass_idx, dest_idx)
                        if pass_idx < 4 and pass_idx != dest_idx:
                            initial_state_distrib[state] += 1
                        for action in range(num_actions):
                            # defaults

            

Reported by Pylint.

Method could be a function
Error

Line: 134 Column: 5

                          self, num_states, num_actions, P, initial_state_distrib
        )

    def encode(self, taxi_row, taxi_col, pass_loc, dest_idx):
        # (5) 5, 5, 4
        i = taxi_row
        i *= 5
        i += taxi_col
        i *= 5

            

Reported by Pylint.

gym/envs/toy_text/frozen_lake.py
19 issues
Missing module docstring
Error

Line: 1 Column: 1

              import sys
from contextlib import closing

import numpy as np
from io import StringIO

from gym import utils
from gym.envs.toy_text import discrete


            

Reported by Pylint.

standard import "from io import StringIO" should be placed before "import numpy as np"
Error

Line: 5 Column: 1

              from contextlib import closing

import numpy as np
from io import StringIO

from gym import utils
from gym.envs.toy_text import discrete

LEFT = 0

            

Reported by Pylint.

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

Line: 30 Column: 1

              }


def generate_random_map(size=8, p=0.8):
    """Generates a random valid map (one that has a path from start to goal)
    :param size: size of each side of the grid
    :param p: probability that a tile is frozen
    """
    valid = False

            

Reported by Pylint.

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

Line: 42 Column: 16

                      frontier, discovered = [], set()
        frontier.append((0, 0))
        while frontier:
            r, c = frontier.pop()
            if not (r, c) in discovered:
                discovered.add((r, c))
                directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
                for x, y in directions:
                    r_new = r + x

            

Reported by Pylint.

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

Line: 42 Column: 13

                      frontier, discovered = [], set()
        frontier.append((0, 0))
        while frontier:
            r, c = frontier.pop()
            if not (r, c) in discovered:
                discovered.add((r, c))
                directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
                for x, y in directions:
                    r_new = r + x

            

Reported by Pylint.

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

Line: 46 Column: 24

                          if not (r, c) in discovered:
                discovered.add((r, c))
                directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
                for x, y in directions:
                    r_new = r + x
                    c_new = c + y
                    if r_new < 0 or r_new >= size or c_new < 0 or c_new >= size:
                        continue
                    if res[r_new][c_new] == "G":

            

Reported by Pylint.

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

Line: 46 Column: 21

                          if not (r, c) in discovered:
                discovered.add((r, c))
                directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
                for x, y in directions:
                    r_new = r + x
                    c_new = c + y
                    if r_new < 0 or r_new >= size or c_new < 0 or c_new >= size:
                        continue
                    if res[r_new][c_new] == "G":

            

Reported by Pylint.

Too many local variables (20/15)
Error

Line: 94 Column: 5

              
    metadata = {"render.modes": ["human", "ansi"]}

    def __init__(self, desc=None, map_name="4x4", is_slippery=True):
        if desc is None and map_name is None:
            desc = generate_random_map()
        elif desc is None:
            desc = MAPS[map_name]
        self.desc = desc = np.asarray(desc, dtype="c")

            

Reported by Pylint.

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

Line: 103 Column: 9

                      self.nrow, self.ncol = nrow, ncol = desc.shape
        self.reward_range = (0, 1)

        nA = 4
        nS = nrow * ncol

        isd = np.array(desc == b"S").astype("float64").ravel()
        isd /= isd.sum()


            

Reported by Pylint.

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

Line: 104 Column: 9

                      self.reward_range = (0, 1)

        nA = 4
        nS = nrow * ncol

        isd = np.array(desc == b"S").astype("float64").ravel()
        isd /= isd.sum()

        P = {s: {a: [] for a in range(nA)} for s in range(nS)}

            

Reported by Pylint.

gym/envs/tests/test_envs.py
19 issues
Unable to import 'pytest'
Error

Line: 1 Column: 1

              import pytest
import numpy as np

from gym import envs
from gym.envs.tests.spec_list import spec_list
from gym.utils.env_checker import check_env


# This runs a smoketest on each official registered env. We may want

            

Reported by Pylint.

Cell variable env defined in loop
Error

Line: 50 Column: 28

              # Run a longer rollout on some environments
def test_random_rollout():
    for env in [envs.make("CartPole-v0"), 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)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import pytest
import numpy as np

from gym import envs
from gym.envs.tests.spec_list import spec_list
from gym.utils.env_checker import check_env


# This runs a smoketest on each official registered env. We may want

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 13 Column: 1

              # to try also running environments which are not officially registered
# envs.
@pytest.mark.parametrize("spec", spec_list)
def test_env(spec):
    # Capture warnings
    with pytest.warns(None) as warnings:
        env = spec.make()

    # Test if env adheres to Gym API

            

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

              
    # Check that dtype is explicitly declared for gym.Box spaces
    for warning_msg in warnings:
        assert "autodetected dtype" not in str(warning_msg.message)

    ob_space = env.observation_space
    act_space = env.action_space
    ob = env.reset()
    assert ob_space.contains(ob), "Reset observation: {!r} not in space".format(ob)

            

Reported by Bandit.

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

Line: 27 Column: 5

              
    ob_space = env.observation_space
    act_space = env.action_space
    ob = env.reset()
    assert ob_space.contains(ob), "Reset observation: {!r} not in space".format(ob)
    a = act_space.sample()
    observation, reward, done, _info = env.step(a)
    assert ob_space.contains(observation), "Step observation: {!r} not in space".format(
        observation

            

Reported by Pylint.

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

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

                  ob_space = env.observation_space
    act_space = env.action_space
    ob = env.reset()
    assert ob_space.contains(ob), "Reset observation: {!r} not in space".format(ob)
    a = act_space.sample()
    observation, reward, done, _info = env.step(a)
    assert ob_space.contains(observation), "Step observation: {!r} not in space".format(
        observation
    )

            

Reported by Bandit.

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

Line: 29 Column: 5

                  act_space = env.action_space
    ob = env.reset()
    assert ob_space.contains(ob), "Reset observation: {!r} not in space".format(ob)
    a = act_space.sample()
    observation, reward, done, _info = env.step(a)
    assert ob_space.contains(observation), "Step observation: {!r} not in space".format(
        observation
    )
    assert np.isscalar(reward), "{} is not a scalar for {}".format(reward, env)

            

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

                  assert ob_space.contains(ob), "Reset observation: {!r} not in space".format(ob)
    a = act_space.sample()
    observation, reward, done, _info = env.step(a)
    assert ob_space.contains(observation), "Step observation: {!r} not in space".format(
        observation
    )
    assert np.isscalar(reward), "{} is not a scalar for {}".format(reward, env)
    assert isinstance(done, bool), "Expected {} to be a boolean".format(done)


            

Reported by Bandit.

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

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

                  assert ob_space.contains(observation), "Step observation: {!r} not in space".format(
        observation
    )
    assert np.isscalar(reward), "{} is not a scalar for {}".format(reward, env)
    assert isinstance(done, bool), "Expected {} to be a boolean".format(done)

    for mode in env.metadata.get("render.modes", []):
        env.render(mode=mode)


            

Reported by Bandit.

gym/envs/robotics/fetch_env.py
19 issues
Parameters differ from overridden 'compute_reward' method
Error

Line: 65 Column: 5

                  # GoalEnv methods
    # ----------------------------

    def compute_reward(self, achieved_goal, goal, info):
        # Compute distance between goal and the achieved goal.
        d = goal_distance(achieved_goal, goal)
        if self.reward_type == "sparse":
            return -(d > self.distance_threshold).astype(np.float32)
        else:

            

Reported by Pylint.

Useless super delegation in method 'render'
Error

Line: 229 Column: 5

                      if self.has_object:
            self.height_offset = self.sim.data.get_site_xpos("object0")[2]

    def render(self, mode="human", width=500, height=500):
        return super(FetchEnv, self).render(mode, width, height)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np

from gym.envs.robotics import rotations, robot_env, utils


def goal_distance(goal_a, goal_b):
    assert goal_a.shape == goal_b.shape
    return np.linalg.norm(goal_a - goal_b, axis=-1)


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 6 Column: 1

              from gym.envs.robotics import rotations, robot_env, utils


def goal_distance(goal_a, goal_b):
    assert goal_a.shape == goal_b.shape
    return np.linalg.norm(goal_a - goal_b, axis=-1)


class FetchEnv(robot_env.RobotEnv):

            

Reported by Pylint.

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

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

              

def goal_distance(goal_a, goal_b):
    assert goal_a.shape == goal_b.shape
    return np.linalg.norm(goal_a - goal_b, axis=-1)


class FetchEnv(robot_env.RobotEnv):
    """Superclass for all Fetch environments."""

            

Reported by Bandit.

Too many instance attributes (11/7)
Error

Line: 11 Column: 1

                  return np.linalg.norm(goal_a - goal_b, axis=-1)


class FetchEnv(robot_env.RobotEnv):
    """Superclass for all Fetch environments."""

    def __init__(
        self,
        model_path,

            

Reported by Pylint.

Too many arguments (13/5)
Error

Line: 14 Column: 5

              class FetchEnv(robot_env.RobotEnv):
    """Superclass for all Fetch environments."""

    def __init__(
        self,
        model_path,
        n_substeps,
        gripper_extra_height,
        block_gripper,

            

Reported by Pylint.

Line too long (104/100)
Error

Line: 34 Column: 1

                      Args:
            model_path (string): path to the environments XML file
            n_substeps (int): number of substeps the simulation runs on every call to step
            gripper_extra_height (float): additional height above the table when positioning the gripper
            block_gripper (boolean): whether or not the gripper is blocked (i.e. not movable) or not
            has_object (boolean): whether or not the environment has an object
            target_in_the_air (boolean): whether or not the target should be in the air above the table or on the table surface
            target_offset (float or array with 3 elements): offset of the target
            obj_range (float): range of a uniform distribution for sampling initial object positions

            

Reported by Pylint.

Line too long (127/100)
Error

Line: 37 Column: 1

                          gripper_extra_height (float): additional height above the table when positioning the gripper
            block_gripper (boolean): whether or not the gripper is blocked (i.e. not movable) or not
            has_object (boolean): whether or not the environment has an object
            target_in_the_air (boolean): whether or not the target should be in the air above the table or on the table surface
            target_offset (float or array with 3 elements): offset of the target
            obj_range (float): range of a uniform distribution for sampling initial object positions
            target_range (float): range of a uniform distribution for sampling a target
            distance_threshold (float): the threshold after which a goal is considered achieved
            initial_qpos (dict): a dictionary of joint names and values that define the initial configuration

            

Reported by Pylint.

Line too long (109/100)
Error

Line: 42 Column: 1

                          obj_range (float): range of a uniform distribution for sampling initial object positions
            target_range (float): range of a uniform distribution for sampling a target
            distance_threshold (float): the threshold after which a goal is considered achieved
            initial_qpos (dict): a dictionary of joint names and values that define the initial configuration
            reward_type ('sparse' or 'dense'): the reward type, i.e. sparse or dense
        """
        self.gripper_extra_height = gripper_extra_height
        self.block_gripper = block_gripper
        self.has_object = has_object

            

Reported by Pylint.