The following issues were found

gym/envs/mujoco/humanoid_v3.py
12 issues
Unused argument 'action'
Error

Line: 59 Column: 28

                          * self._healthy_reward
        )

    def control_cost(self, action):
        control_cost = self._ctrl_cost_weight * np.sum(np.square(self.sim.data.ctrl))
        return control_cost

    @property
    def contact_cost(self):

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np
from gym.envs.mujoco import mujoco_env
from gym import utils


DEFAULT_CAMERA_CONFIG = {
    "trackbodyid": 1,
    "distance": 4.0,
    "lookat": np.array((0.0, 0.0, 2.0)),

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 14 Column: 1

              }


def mass_center(model, sim):
    mass = np.expand_dims(model.body_mass, axis=1)
    xpos = sim.data.xipos
    return (np.sum(mass * xpos, axis=0) / np.sum(mass))[0:2].copy()



            

Reported by Pylint.

Missing class docstring
Error

Line: 20 Column: 1

                  return (np.sum(mass * xpos, axis=0) / np.sum(mass))[0:2].copy()


class HumanoidEnv(mujoco_env.MujocoEnv, utils.EzPickle):
    def __init__(
        self,
        xml_file="humanoid.xml",
        forward_reward_weight=1.25,
        ctrl_cost_weight=0.1,

            

Reported by Pylint.

Too many instance attributes (9/7)
Error

Line: 20 Column: 1

                  return (np.sum(mass * xpos, axis=0) / np.sum(mass))[0:2].copy()


class HumanoidEnv(mujoco_env.MujocoEnv, utils.EzPickle):
    def __init__(
        self,
        xml_file="humanoid.xml",
        forward_reward_weight=1.25,
        ctrl_cost_weight=0.1,

            

Reported by Pylint.

Too many arguments (11/5)
Error

Line: 21 Column: 5

              

class HumanoidEnv(mujoco_env.MujocoEnv, utils.EzPickle):
    def __init__(
        self,
        xml_file="humanoid.xml",
        forward_reward_weight=1.25,
        ctrl_cost_weight=0.1,
        contact_cost_weight=5e-7,

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 53 Column: 5

                      mujoco_env.MujocoEnv.__init__(self, xml_file, 5)

    @property
    def healthy_reward(self):
        return (
            float(self.is_healthy or self._terminate_when_unhealthy)
            * self._healthy_reward
        )


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 59 Column: 5

                          * self._healthy_reward
        )

    def control_cost(self, action):
        control_cost = self._ctrl_cost_weight * np.sum(np.square(self.sim.data.ctrl))
        return control_cost

    @property
    def contact_cost(self):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 64 Column: 5

                      return control_cost

    @property
    def contact_cost(self):
        contact_forces = self.sim.data.cfrc_ext
        contact_cost = self._contact_cost_weight * np.sum(np.square(contact_forces))
        min_cost, max_cost = self._contact_cost_range
        contact_cost = np.clip(contact_cost, min_cost, max_cost)
        return contact_cost

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 72 Column: 5

                      return contact_cost

    @property
    def is_healthy(self):
        min_z, max_z = self._healthy_z_range
        is_healthy = min_z < self.sim.data.qpos[2] < max_z

        return is_healthy


            

Reported by Pylint.

gym/envs/tests/test_frozenlake_dfs.py
12 issues
Unable to import 'pytest'
Error

Line: 1 Column: 1

              import pytest
import numpy as np

from gym.envs.toy_text.frozen_lake import generate_random_map


# Test that FrozenLake map generation creates valid maps of various sizes.
def test_frozenlake_dfs_map_generation():
    def frozenlake_dfs_path_exists(res):

            

Reported by Pylint.

Unused import pytest
Error

Line: 1 Column: 1

              import pytest
import numpy as np

from gym.envs.toy_text.frozen_lake import generate_random_map


# Test that FrozenLake map generation creates valid maps of various sizes.
def test_frozenlake_dfs_map_generation():
    def frozenlake_dfs_path_exists(res):

            

Reported by Pylint.

Unused numpy imported as np
Error

Line: 2 Column: 1

              import pytest
import numpy as np

from gym.envs.toy_text.frozen_lake import generate_random_map


# Test that FrozenLake map generation creates valid maps of various sizes.
def test_frozenlake_dfs_map_generation():
    def frozenlake_dfs_path_exists(res):

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import pytest
import numpy as np

from gym.envs.toy_text.frozen_lake import generate_random_map


# Test that FrozenLake map generation creates valid maps of various sizes.
def test_frozenlake_dfs_map_generation():
    def frozenlake_dfs_path_exists(res):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 8 Column: 1

              

# Test that FrozenLake map generation creates valid maps of various sizes.
def test_frozenlake_dfs_map_generation():
    def frozenlake_dfs_path_exists(res):
        frontier, discovered = [], set()
        frontier.append((0, 0))
        while frontier:
            r, c = frontier.pop()

            

Reported by Pylint.

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

Line: 13 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: 13 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: 17 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: 17 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.

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

                  map_sizes = [5, 10, 200]
    for size in map_sizes:
        new_frozenlake = generate_random_map(size)
        assert len(new_frozenlake) == size
        assert len(new_frozenlake[0]) == size
        assert frozenlake_dfs_path_exists(new_frozenlake)

            

Reported by Bandit.

gym/envs/tests/spec_list.py
11 issues
Unused import mujoco_py
Error

Line: 14 Column: 9

              skip_mujoco = not (os.environ.get("MUJOCO_KEY"))
if not skip_mujoco:
    try:
        import mujoco_py
    except ImportError:
        skip_mujoco = True


def should_skip_env_spec_for_tests(spec):

            

Reported by Pylint.

Unused import atari_py
Error

Line: 29 Column: 9

                  ):
        return True
    try:
        import atari_py
    except ImportError:
        if ep.startswith("gym.envs.atari"):
            return True
    try:
        import Box2D

            

Reported by Pylint.

Unused import Box2D
Error

Line: 34 Column: 9

                      if ep.startswith("gym.envs.atari"):
            return True
    try:
        import Box2D
    except ImportError:
        if ep.startswith("gym.envs.box2d"):
            return True

    if (

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from gym import envs, logger
import os


SKIP_MUJOCO_WARNING_MESSAGE = (
    "Cannot run mujoco test (either license key not found or mujoco not"
    "installed properly)."
)


            

Reported by Pylint.

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

Line: 2 Column: 1

              from gym import envs, logger
import os


SKIP_MUJOCO_WARNING_MESSAGE = (
    "Cannot run mujoco test (either license key not found or mujoco not"
    "installed properly)."
)


            

Reported by Pylint.

Unnecessary parens after 'not' keyword
Error

Line: 11 Column: 1

              )


skip_mujoco = not (os.environ.get("MUJOCO_KEY"))
if not skip_mujoco:
    try:
        import mujoco_py
    except ImportError:
        skip_mujoco = True

            

Reported by Pylint.

Constant name "skip_mujoco" doesn't conform to UPPER_CASE naming style
Error

Line: 16 Column: 9

                  try:
        import mujoco_py
    except ImportError:
        skip_mujoco = True


def should_skip_env_spec_for_tests(spec):
    # We skip tests for envs that require dependencies or are otherwise
    # troublesome to run frequently

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 19 Column: 1

                      skip_mujoco = True


def should_skip_env_spec_for_tests(spec):
    # We skip tests for envs that require dependencies or are otherwise
    # troublesome to run frequently
    ep = spec.entry_point
    # Skip mujoco tests for pull request CI
    if skip_mujoco and (

            

Reported by Pylint.

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

Line: 22 Column: 5

              def should_skip_env_spec_for_tests(spec):
    # We skip tests for envs that require dependencies or are otherwise
    # troublesome to run frequently
    ep = spec.entry_point
    # Skip mujoco tests for pull request CI
    if skip_mujoco and (
        ep.startswith("gym.envs.mujoco") or ep.startswith("gym.envs.robotics:")
    ):
        return True

            

Reported by Pylint.

Import outside toplevel (atari_py)
Error

Line: 29 Column: 9

                  ):
        return True
    try:
        import atari_py
    except ImportError:
        if ep.startswith("gym.envs.atari"):
            return True
    try:
        import Box2D

            

Reported by Pylint.

gym/envs/mujoco/ant_v3.py
11 issues
Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np
from gym import utils
from gym.envs.mujoco import mujoco_env


DEFAULT_CAMERA_CONFIG = {
    "distance": 4.0,
}


            

Reported by Pylint.

Missing class docstring
Error

Line: 11 Column: 1

              }


class AntEnv(mujoco_env.MujocoEnv, utils.EzPickle):
    def __init__(
        self,
        xml_file="ant.xml",
        ctrl_cost_weight=0.5,
        contact_cost_weight=5e-4,

            

Reported by Pylint.

Too many instance attributes (8/7)
Error

Line: 11 Column: 1

              }


class AntEnv(mujoco_env.MujocoEnv, utils.EzPickle):
    def __init__(
        self,
        xml_file="ant.xml",
        ctrl_cost_weight=0.5,
        contact_cost_weight=5e-4,

            

Reported by Pylint.

Too many arguments (10/5)
Error

Line: 12 Column: 5

              

class AntEnv(mujoco_env.MujocoEnv, utils.EzPickle):
    def __init__(
        self,
        xml_file="ant.xml",
        ctrl_cost_weight=0.5,
        contact_cost_weight=5e-4,
        healthy_reward=1.0,

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 44 Column: 5

                      mujoco_env.MujocoEnv.__init__(self, xml_file, 5)

    @property
    def healthy_reward(self):
        return (
            float(self.is_healthy or self._terminate_when_unhealthy)
            * self._healthy_reward
        )


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 50 Column: 5

                          * self._healthy_reward
        )

    def control_cost(self, action):
        control_cost = self._ctrl_cost_weight * np.sum(np.square(action))
        return control_cost

    @property
    def contact_forces(self):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 55 Column: 5

                      return control_cost

    @property
    def contact_forces(self):
        raw_contact_forces = self.sim.data.cfrc_ext
        min_value, max_value = self._contact_force_range
        contact_forces = np.clip(raw_contact_forces, min_value, max_value)
        return contact_forces


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 62 Column: 5

                      return contact_forces

    @property
    def contact_cost(self):
        contact_cost = self._contact_cost_weight * np.sum(
            np.square(self.contact_forces)
        )
        return contact_cost


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 69 Column: 5

                      return contact_cost

    @property
    def is_healthy(self):
        state = self.state_vector()
        min_z, max_z = self._healthy_z_range
        is_healthy = np.isfinite(state).all() and min_z <= state[2] <= max_z
        return is_healthy


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 76 Column: 5

                      return is_healthy

    @property
    def done(self):
        done = not self.is_healthy if self._terminate_when_unhealthy else False
        return done

    def step(self, action):
        xy_position_before = self.get_body_com("torso")[:2].copy()

            

Reported by Pylint.

gym/envs/robotics/hand/reach.py
11 issues
Dangerous default value DEFAULT_INITIAL_QPOS (builtins.dict) as argument
Error

Line: 56 Column: 5

              

class HandReachEnv(hand_env.HandEnv, utils.EzPickle):
    def __init__(
        self,
        distance_threshold=0.01,
        n_substeps=20,
        relative_control=False,
        initial_qpos=DEFAULT_INITIAL_QPOS,

            

Reported by Pylint.

Parameters differ from overridden 'compute_reward' method
Error

Line: 83 Column: 5

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

    def compute_reward(self, achieved_goal, goal, info):
        d = goal_distance(achieved_goal, goal)
        if self.reward_type == "sparse":
            return -(d > self.distance_threshold).astype(np.float32)
        else:
            return -d

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import os
import numpy as np

from gym import utils
from gym.envs.robotics import hand_env
from gym.envs.robotics.utils import robot_get_obs


FINGERTIP_SITE_NAMES = [

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 50 Column: 1

              MODEL_XML_PATH = os.path.join("hand", "reach.xml")


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 HandReachEnv(hand_env.HandEnv, utils.EzPickle):

            

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

              

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 HandReachEnv(hand_env.HandEnv, utils.EzPickle):
    def __init__(

            

Reported by Bandit.

Missing class docstring
Error

Line: 55 Column: 1

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


class HandReachEnv(hand_env.HandEnv, utils.EzPickle):
    def __init__(
        self,
        distance_threshold=0.01,
        n_substeps=20,
        relative_control=False,

            

Reported by Pylint.

Too many arguments (6/5)
Error

Line: 56 Column: 5

              

class HandReachEnv(hand_env.HandEnv, utils.EzPickle):
    def __init__(
        self,
        distance_threshold=0.01,
        n_substeps=20,
        relative_control=False,
        initial_qpos=DEFAULT_INITIAL_QPOS,

            

Reported by Pylint.

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

Line: 84 Column: 9

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

    def compute_reward(self, achieved_goal, goal, info):
        d = goal_distance(achieved_goal, goal)
        if self.reward_type == "sparse":
            return -(d > self.distance_threshold).astype(np.float32)
        else:
            return -d


            

Reported by Pylint.

Unnecessary "else" after "return"
Error

Line: 85 Column: 9

              
    def compute_reward(self, achieved_goal, goal, info):
        d = goal_distance(achieved_goal, goal)
        if self.reward_type == "sparse":
            return -(d > self.distance_threshold).astype(np.float32)
        else:
            return -d

    # RobotEnv methods

            

Reported by Pylint.

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

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

              
        thumb_idx = FINGERTIP_SITE_NAMES.index(thumb_name)
        finger_idx = FINGERTIP_SITE_NAMES.index(finger_name)
        assert thumb_idx != finger_idx

        # Pick a meeting point above the hand.
        meeting_pos = self.palm_xpos + np.array([0.0, -0.09, 0.05])
        meeting_pos += self.np_random.normal(scale=0.005, size=meeting_pos.shape)


            

Reported by Bandit.

gym/vector/utils/misc.py
11 issues
Unable to import 'cloudpickle'
Error

Line: 12 Column: 9

                      self.fn = fn

    def __getstate__(self):
        import cloudpickle

        return cloudpickle.dumps(self.fn)

    def __setstate__(self, ob):
        import pickle

            

Reported by Pylint.

Pickle and modules that wrap it can be unsafe when used to deserialize untrusted data, possible security issue.
Security blacklist

Line: 19
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_calls.html#b301-pickle

                  def __setstate__(self, ob):
        import pickle

        self.fn = pickle.loads(ob)

    def __call__(self):
        return self.fn()



            

Reported by Bandit.

Missing module docstring
Error

Line: 1 Column: 1

              import contextlib
import os

__all__ = ["CloudpickleWrapper", "clear_mpi_env_vars"]


class CloudpickleWrapper(object):
    def __init__(self, fn):
        self.fn = fn

            

Reported by Pylint.

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

Line: 7 Column: 1

              __all__ = ["CloudpickleWrapper", "clear_mpi_env_vars"]


class CloudpickleWrapper(object):
    def __init__(self, fn):
        self.fn = fn

    def __getstate__(self):
        import cloudpickle

            

Reported by Pylint.

Missing class docstring
Error

Line: 7 Column: 1

              __all__ = ["CloudpickleWrapper", "clear_mpi_env_vars"]


class CloudpickleWrapper(object):
    def __init__(self, fn):
        self.fn = fn

    def __getstate__(self):
        import cloudpickle

            

Reported by Pylint.

Attribute name "fn" doesn't conform to snake_case naming style
Error

Line: 9 Column: 9

              
class CloudpickleWrapper(object):
    def __init__(self, fn):
        self.fn = fn

    def __getstate__(self):
        import cloudpickle

        return cloudpickle.dumps(self.fn)

            

Reported by Pylint.

Import outside toplevel (cloudpickle)
Error

Line: 12 Column: 9

                      self.fn = fn

    def __getstate__(self):
        import cloudpickle

        return cloudpickle.dumps(self.fn)

    def __setstate__(self, ob):
        import pickle

            

Reported by Pylint.

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

Line: 16 Column: 5

              
        return cloudpickle.dumps(self.fn)

    def __setstate__(self, ob):
        import pickle

        self.fn = pickle.loads(ob)

    def __call__(self):

            

Reported by Pylint.

Import outside toplevel (pickle)
Error

Line: 17 Column: 9

                      return cloudpickle.dumps(self.fn)

    def __setstate__(self, ob):
        import pickle

        self.fn = pickle.loads(ob)

    def __call__(self):
        return self.fn()

            

Reported by Pylint.

Consider possible security implications associated with pickle module.
Security blacklist

Line: 17
Suggestion: https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b403-import-pickle

                      return cloudpickle.dumps(self.fn)

    def __setstate__(self, ob):
        import pickle

        self.fn = pickle.loads(ob)

    def __call__(self):
        return self.fn()

            

Reported by Bandit.

gym/vector/sync_vector_env.py
11 issues
Unused logger imported from gym
Error

Line: 4 Column: 1

              import numpy as np
from copy import deepcopy

from gym import logger
from gym.vector.vector_env import VectorEnv
from gym.vector.utils import concatenate, create_empty_array

__all__ = ["SyncVectorEnv"]


            

Reported by Pylint.

Method 'render' is abstract in class 'Env' but is not overridden
Error

Line: 11 Column: 1

              __all__ = ["SyncVectorEnv"]


class SyncVectorEnv(VectorEnv):
    """Vectorized environment that serially runs multiple environments.

    Parameters
    ----------
    env_fns : iterable of callable

            

Reported by Pylint.

Parameters differ from overridden 'reset_wait' method
Error

Line: 65 Column: 5

                      for env, seed in zip(self.envs, seeds):
            env.seed(seed)

    def reset_wait(self):
        self._dones[:] = False
        observations = []
        for env in self.envs:
            observation = env.reset()
            observations.append(observation)

            

Reported by Pylint.

Parameters differ from overridden 'step_wait' method
Error

Line: 80 Column: 5

                  def step_async(self, actions):
        self._actions = actions

    def step_wait(self):
        observations, infos = [], []
        for i, (env, action) in enumerate(zip(self.envs, self._actions)):
            observation, self._rewards[i], self._dones[i], info = env.step(action)
            if self._dones[i]:
                observation = env.reset()

            

Reported by Pylint.

Expression "[env.close() for env in self.envs]" is assigned to nothing
Error

Line: 100 Column: 9

                      )

    def close_extras(self, **kwargs):
        [env.close() for env in self.envs]

    def _check_observation_spaces(self):
        for env in self.envs:
            if not (env.observation_space == self.single_observation_space):
                break

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np
from copy import deepcopy

from gym import logger
from gym.vector.vector_env import VectorEnv
from gym.vector.utils import concatenate, create_empty_array

__all__ = ["SyncVectorEnv"]


            

Reported by Pylint.

standard import "from copy import deepcopy" should be placed before "import numpy as np"
Error

Line: 2 Column: 1

              import numpy as np
from copy import deepcopy

from gym import logger
from gym.vector.vector_env import VectorEnv
from gym.vector.utils import concatenate, create_empty_array

__all__ = ["SyncVectorEnv"]


            

Reported by Pylint.

Too many instance attributes (8/7)
Error

Line: 11 Column: 1

              __all__ = ["SyncVectorEnv"]


class SyncVectorEnv(VectorEnv):
    """Vectorized environment that serially runs multiple environments.

    Parameters
    ----------
    env_fns : iterable of callable

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 41 Column: 9

                      if (observation_space is None) or (action_space is None):
            observation_space = observation_space or self.envs[0].observation_space
            action_space = action_space or self.envs[0].action_space
        super(SyncVectorEnv, self).__init__(
            num_envs=len(env_fns),
            observation_space=observation_space,
            action_space=action_space,
        )


            

Reported by Pylint.

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

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

                          seeds = [None for _ in range(self.num_envs)]
        if isinstance(seeds, int):
            seeds = [seeds + i for i in range(self.num_envs)]
        assert len(seeds) == self.num_envs

        for env, seed in zip(self.envs, seeds):
            env.seed(seed)

    def reset_wait(self):

            

Reported by Bandit.

gym/envs/toy_text/cliffwalking.py
11 issues
Missing module docstring
Error

Line: 1 Column: 1

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

UP = 0
RIGHT = 1
DOWN = 2

            

Reported by Pylint.

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

Line: 2 Column: 1

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

UP = 0
RIGHT = 1
DOWN = 2

            

Reported by Pylint.

standard import "from contextlib import closing" should be placed before "import numpy as np"
Error

Line: 3 Column: 1

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

UP = 0
RIGHT = 1
DOWN = 2

            

Reported by Pylint.

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

Line: 4 Column: 1

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

UP = 0
RIGHT = 1
DOWN = 2

            

Reported by Pylint.

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

Line: 40 Column: 9

                      self.shape = (4, 12)
        self.start_state_index = np.ravel_multi_index((3, 0), self.shape)

        nS = np.prod(self.shape)
        nA = 4

        # Cliff Location
        self._cliff = np.zeros(self.shape, dtype=np.bool)
        self._cliff[3, 1:-1] = True

            

Reported by Pylint.

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

Line: 41 Column: 9

                      self.start_state_index = np.ravel_multi_index((3, 0), self.shape)

        nS = np.prod(self.shape)
        nA = 4

        # Cliff Location
        self._cliff = np.zeros(self.shape, dtype=np.bool)
        self._cliff[3, 1:-1] = True


            

Reported by Pylint.

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

Line: 48 Column: 9

                      self._cliff[3, 1:-1] = True

        # Calculate transition probabilities and rewards
        P = {}
        for s in range(nS):
            position = np.unravel_index(s, self.shape)
            P[s] = {a: [] for a in range(nA)}
            P[s][UP] = self._calculate_transition_prob(position, [-1, 0])
            P[s][RIGHT] = self._calculate_transition_prob(position, [0, 1])

            

Reported by Pylint.

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

Line: 49 Column: 13

              
        # Calculate transition probabilities and rewards
        P = {}
        for s in range(nS):
            position = np.unravel_index(s, self.shape)
            P[s] = {a: [] for a in range(nA)}
            P[s][UP] = self._calculate_transition_prob(position, [-1, 0])
            P[s][RIGHT] = self._calculate_transition_prob(position, [0, 1])
            P[s][DOWN] = self._calculate_transition_prob(position, [1, 0])

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 62 Column: 9

                      isd = np.zeros(nS)
        isd[self.start_state_index] = 1.0

        super(CliffWalkingEnv, self).__init__(nS, nA, P, isd)

    def _limit_coordinates(self, coord):
        """
        Prevent the agent from falling out of the grid world
        :param coord:

            

Reported by Pylint.

Either all return statements in a function should return an expression, or none of them should.
Error

Line: 93 Column: 5

                      is_done = tuple(new_position) == terminal_state
        return [(1.0, new_state, -1, is_done)]

    def render(self, mode="human"):
        outfile = StringIO() if mode == "ansi" else sys.stdout

        for s in range(self.nS):
            position = np.unravel_index(s, self.shape)
            if self.s == s:

            

Reported by Pylint.

gym/spaces/discrete.py
10 issues
Attempted relative import beyond top-level package
Error

Line: 2 Column: 1

              import numpy as np
from .space import Space


class Discrete(Space):
    r"""A discrete space in :math:`\{ 0, 1, \\dots, n-1 \}`.

    Example::


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np
from .space import Space


class Discrete(Space):
    r"""A discrete space in :math:`\{ 0, 1, \\dots, n-1 \}`.

    Example::


            

Reported by Pylint.

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

Line: 14 Column: 5

              
    """

    def __init__(self, n):
        assert n >= 0
        self.n = n
        super(Discrete, self).__init__((), np.int64)

    def sample(self):

            

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

                  """

    def __init__(self, n):
        assert n >= 0
        self.n = n
        super(Discrete, self).__init__((), np.int64)

    def sample(self):
        return self.np_random.randint(self.n)

            

Reported by Bandit.

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

Line: 16 Column: 9

              
    def __init__(self, n):
        assert n >= 0
        self.n = n
        super(Discrete, self).__init__((), np.int64)

    def sample(self):
        return self.np_random.randint(self.n)


            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 17 Column: 9

                  def __init__(self, n):
        assert n >= 0
        self.n = n
        super(Discrete, self).__init__((), np.int64)

    def sample(self):
        return self.np_random.randint(self.n)

    def contains(self, x):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 19 Column: 5

                      self.n = n
        super(Discrete, self).__init__((), np.int64)

    def sample(self):
        return self.np_random.randint(self.n)

    def contains(self, x):
        if isinstance(x, int):
            as_int = x

            

Reported by Pylint.

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

Line: 22 Column: 5

                  def sample(self):
        return self.np_random.randint(self.n)

    def contains(self, x):
        if isinstance(x, int):
            as_int = x
        elif isinstance(x, (np.generic, np.ndarray)) and (
            x.dtype.char in np.typecodes["AllInteger"] and x.shape == ()
        ):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 22 Column: 5

                  def sample(self):
        return self.np_random.randint(self.n)

    def contains(self, x):
        if isinstance(x, int):
            as_int = x
        elif isinstance(x, (np.generic, np.ndarray)) and (
            x.dtype.char in np.typecodes["AllInteger"] and x.shape == ()
        ):

            

Reported by Pylint.

Simplify chained comparison between the operands
Error

Line: 31 Column: 16

                          as_int = int(x)
        else:
            return False
        return as_int >= 0 and as_int < self.n

    def __repr__(self):
        return "Discrete(%d)" % self.n

    def __eq__(self, other):

            

Reported by Pylint.

gym/envs/__init__.py
10 issues
Missing module docstring
Error

Line: 1 Column: 1

              from gym.envs.registration import registry, register, make, spec

# Algorithmic
# ----------------------------------------

register(
    id="Copy-v0",
    entry_point="gym.envs.algorithmic:CopyEnv",
    max_episode_steps=200,

            

Reported by Pylint.

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

Line: 339 Column: 1

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


def _merge(a, b):
    a.update(b)
    return a


for reward_type in ["sparse", "dense"]:

            

Reported by Pylint.

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

Line: 339 Column: 1

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


def _merge(a, b):
    a.update(b)
    return a


for reward_type in ["sparse", "dense"]:

            

Reported by Pylint.

Constant name "suffix" doesn't conform to UPPER_CASE naming style
Error

Line: 345 Column: 5

              

for reward_type in ["sparse", "dense"]:
    suffix = "Dense" if reward_type == "dense" else ""
    kwargs = {
        "reward_type": reward_type,
    }

    # Fetch

            

Reported by Pylint.

Constant name "name" doesn't conform to UPPER_CASE naming style
Error

Line: 763 Column: 9

              ]:
    for obs_type in ["image", "ram"]:
        # space_invaders should yield SpaceInvaders-v0 and SpaceInvaders-ram-v0
        name = "".join([g.capitalize() for g in game.split("_")])
        if obs_type == "ram":
            name = "{}-ram".format(name)

        nondeterministic = False
        if game == "elevator_action" and obs_type == "ram":

            

Reported by Pylint.

Constant name "name" doesn't conform to UPPER_CASE naming style
Error

Line: 765 Column: 13

                      # space_invaders should yield SpaceInvaders-v0 and SpaceInvaders-ram-v0
        name = "".join([g.capitalize() for g in game.split("_")])
        if obs_type == "ram":
            name = "{}-ram".format(name)

        nondeterministic = False
        if game == "elevator_action" and obs_type == "ram":
            # ElevatorAction-ram-v0 seems to yield slightly
            # non-deterministic observations about 10% of the time. We

            

Reported by Pylint.

Constant name "nondeterministic" doesn't conform to UPPER_CASE naming style
Error

Line: 767 Column: 9

                      if obs_type == "ram":
            name = "{}-ram".format(name)

        nondeterministic = False
        if game == "elevator_action" and obs_type == "ram":
            # ElevatorAction-ram-v0 seems to yield slightly
            # non-deterministic observations about 10% of the time. We
            # should track this down eventually, but for now we just
            # mark it as nondeterministic.

            

Reported by Pylint.

Constant name "nondeterministic" doesn't conform to UPPER_CASE naming style
Error

Line: 773 Column: 13

                          # non-deterministic observations about 10% of the time. We
            # should track this down eventually, but for now we just
            # mark it as nondeterministic.
            nondeterministic = True

        register(
            id="{}-v0".format(name),
            entry_point="gym.envs.atari:AtariEnv",
            kwargs={

            

Reported by Pylint.

Constant name "frameskip" doesn't conform to UPPER_CASE naming style
Error

Line: 797 Column: 13

              
        # Standard Deterministic (as in the original DeepMind paper)
        if game == "space_invaders":
            frameskip = 3
        else:
            frameskip = 4

        # Use a deterministic frame skip.
        register(

            

Reported by Pylint.

Constant name "frameskip" doesn't conform to UPPER_CASE naming style
Error

Line: 799 Column: 13

                      if game == "space_invaders":
            frameskip = 3
        else:
            frameskip = 4

        # Use a deterministic frame skip.
        register(
            id="{}Deterministic-v0".format(name),
            entry_point="gym.envs.atari:AtariEnv",

            

Reported by Pylint.