The following issues were found

gym/wrappers/test_time_aware_observation.py
16 issues
Unable to import 'pytest'
Error

Line: 1 Column: 1

              import pytest

import gym
from gym.wrappers import TimeAwareObservation


@pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v0"])
def test_time_aware_observation(env_id):
    env = gym.make(env_id)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import pytest

import gym
from gym.wrappers import TimeAwareObservation


@pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v0"])
def test_time_aware_observation(env_id):
    env = gym.make(env_id)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 8 Column: 1

              

@pytest.mark.parametrize("env_id", ["CartPole-v1", "Pendulum-v0"])
def test_time_aware_observation(env_id):
    env = gym.make(env_id)
    wrapped_env = TimeAwareObservation(env)

    assert wrapped_env.observation_space.shape[0] == env.observation_space.shape[0] + 1


            

Reported by Pylint.

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

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

                  env = gym.make(env_id)
    wrapped_env = TimeAwareObservation(env)

    assert wrapped_env.observation_space.shape[0] == env.observation_space.shape[0] + 1

    obs = env.reset()
    wrapped_obs = wrapped_env.reset()
    assert wrapped_env.t == 0.0
    assert wrapped_obs[-1] == 0.0

            

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

              
    obs = env.reset()
    wrapped_obs = wrapped_env.reset()
    assert wrapped_env.t == 0.0
    assert wrapped_obs[-1] == 0.0
    assert wrapped_obs.shape[0] == obs.shape[0] + 1

    wrapped_obs, _, _, _ = wrapped_env.step(env.action_space.sample())
    assert wrapped_env.t == 1.0

            

Reported by Bandit.

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

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

                  obs = env.reset()
    wrapped_obs = wrapped_env.reset()
    assert wrapped_env.t == 0.0
    assert wrapped_obs[-1] == 0.0
    assert wrapped_obs.shape[0] == obs.shape[0] + 1

    wrapped_obs, _, _, _ = wrapped_env.step(env.action_space.sample())
    assert wrapped_env.t == 1.0
    assert wrapped_obs[-1] == 1.0

            

Reported by Bandit.

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

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

                  wrapped_obs = wrapped_env.reset()
    assert wrapped_env.t == 0.0
    assert wrapped_obs[-1] == 0.0
    assert wrapped_obs.shape[0] == obs.shape[0] + 1

    wrapped_obs, _, _, _ = wrapped_env.step(env.action_space.sample())
    assert wrapped_env.t == 1.0
    assert wrapped_obs[-1] == 1.0
    assert wrapped_obs.shape[0] == obs.shape[0] + 1

            

Reported by Bandit.

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

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

                  assert wrapped_obs.shape[0] == obs.shape[0] + 1

    wrapped_obs, _, _, _ = wrapped_env.step(env.action_space.sample())
    assert wrapped_env.t == 1.0
    assert wrapped_obs[-1] == 1.0
    assert wrapped_obs.shape[0] == obs.shape[0] + 1

    wrapped_obs, _, _, _ = wrapped_env.step(env.action_space.sample())
    assert wrapped_env.t == 2.0

            

Reported by Bandit.

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

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

              
    wrapped_obs, _, _, _ = wrapped_env.step(env.action_space.sample())
    assert wrapped_env.t == 1.0
    assert wrapped_obs[-1] == 1.0
    assert wrapped_obs.shape[0] == obs.shape[0] + 1

    wrapped_obs, _, _, _ = wrapped_env.step(env.action_space.sample())
    assert wrapped_env.t == 2.0
    assert wrapped_obs[-1] == 2.0

            

Reported by Bandit.

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

                  wrapped_obs, _, _, _ = wrapped_env.step(env.action_space.sample())
    assert wrapped_env.t == 1.0
    assert wrapped_obs[-1] == 1.0
    assert wrapped_obs.shape[0] == obs.shape[0] + 1

    wrapped_obs, _, _, _ = wrapped_env.step(env.action_space.sample())
    assert wrapped_env.t == 2.0
    assert wrapped_obs[-1] == 2.0
    assert wrapped_obs.shape[0] == obs.shape[0] + 1

            

Reported by Bandit.

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.

tests/gym/wrappers/nested_dict_test.py
16 issues
Unable to import 'pytest'
Error

Line: 4 Column: 1

              """Tests for the filter observation wrapper."""


import pytest
import numpy as np

import gym
from gym.spaces import Dict, Box, Discrete, Tuple
from gym.wrappers import FilterObservation, FlattenObservation

            

Reported by Pylint.

Unused Discrete imported from gym.spaces
Error

Line: 8 Column: 1

              import numpy as np

import gym
from gym.spaces import Dict, Box, Discrete, Tuple
from gym.wrappers import FilterObservation, FlattenObservation


class FakeEnvironment(gym.Env):
    def __init__(self, observation_space):

            

Reported by Pylint.

Parameters differ from overridden 'render' method
Error

Line: 18 Column: 5

                      self.obs_keys = self.observation_space.spaces.keys()
        self.action_space = 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: 18 Column: 5

                      self.obs_keys = self.observation_space.spaces.keys()
        self.action_space = 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.

Unused argument 'flat_shape'
Error

Line: 115 Column: 58

                      assert wrapped_env.observation_space.dtype == np.float32

    @pytest.mark.parametrize("observation_space, flat_shape", NESTED_DICT_TEST_CASES)
    def test_nested_dicts_ravel(self, observation_space, flat_shape):
        env = FakeEnvironment(observation_space=observation_space)
        wrapped_env = FlattenObservation(FilterObservation(env, env.obs_keys))
        obs = wrapped_env.reset()
        assert obs.shape == wrapped_env.observation_space.shape

            

Reported by Pylint.

Missing class docstring
Error

Line: 12 Column: 1

              from gym.wrappers import FilterObservation, FlattenObservation


class FakeEnvironment(gym.Env):
    def __init__(self, observation_space):
        self.observation_space = observation_space
        self.obs_keys = self.observation_space.spaces.keys()
        self.action_space = Box(shape=(1,), low=-1, high=1, dtype=np.float32)


            

Reported by Pylint.

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

Line: 100 Column: 1

              )


class TestNestedDictWrapper(object):
    @pytest.mark.parametrize("observation_space, flat_shape", NESTED_DICT_TEST_CASES)
    def test_nested_dicts_size(self, observation_space, flat_shape):
        env = FakeEnvironment(observation_space=observation_space)

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

            

Reported by Pylint.

Missing class docstring
Error

Line: 100 Column: 1

              )


class TestNestedDictWrapper(object):
    @pytest.mark.parametrize("observation_space, flat_shape", NESTED_DICT_TEST_CASES)
    def test_nested_dicts_size(self, observation_space, flat_shape):
        env = FakeEnvironment(observation_space=observation_space)

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

            

Reported by Pylint.

Method could be a function
Error

Line: 102 Column: 5

              
class TestNestedDictWrapper(object):
    @pytest.mark.parametrize("observation_space, flat_shape", NESTED_DICT_TEST_CASES)
    def test_nested_dicts_size(self, observation_space, flat_shape):
        env = FakeEnvironment(observation_space=observation_space)

        # Make sure we are testing the right environment for the test.
        observation_space = env.observation_space
        assert isinstance(observation_space, Dict)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 102 Column: 5

              
class TestNestedDictWrapper(object):
    @pytest.mark.parametrize("observation_space, flat_shape", NESTED_DICT_TEST_CASES)
    def test_nested_dicts_size(self, observation_space, flat_shape):
        env = FakeEnvironment(observation_space=observation_space)

        # Make sure we are testing the right environment for the test.
        observation_space = env.observation_space
        assert isinstance(observation_space, Dict)

            

Reported by Pylint.

gym/envs/robotics/hand/manipulate_touch_sensors.py
15 issues
Unused error imported from gym
Error

Line: 4 Column: 1

              import os
import numpy as np

from gym import utils, error, spaces
from gym.envs.robotics.hand import manipulate

# Ensure we get the path separator correct on windows
MANIPULATE_BLOCK_XML = os.path.join("hand", "manipulate_block_touch_sensors.xml")
MANIPULATE_EGG_XML = os.path.join("hand", "manipulate_egg_touch_sensors.xml")

            

Reported by Pylint.

Dangerous default value {} as argument
Error

Line: 14 Column: 5

              

class ManipulateTouchSensorsEnv(manipulate.ManipulateEnv):
    def __init__(
        self,
        model_path,
        target_position,
        target_rotation,
        target_position_range,

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import os
import numpy as np

from gym import utils, error, spaces
from gym.envs.robotics.hand import manipulate

# Ensure we get the path separator correct on windows
MANIPULATE_BLOCK_XML = os.path.join("hand", "manipulate_block_touch_sensors.xml")
MANIPULATE_EGG_XML = os.path.join("hand", "manipulate_egg_touch_sensors.xml")

            

Reported by Pylint.

Missing class docstring
Error

Line: 13 Column: 1

              MANIPULATE_PEN_XML = os.path.join("hand", "manipulate_pen_touch_sensors.xml")


class ManipulateTouchSensorsEnv(manipulate.ManipulateEnv):
    def __init__(
        self,
        model_path,
        target_position,
        target_rotation,

            

Reported by Pylint.

Too many arguments (16/5)
Error

Line: 14 Column: 5

              

class ManipulateTouchSensorsEnv(manipulate.ManipulateEnv):
    def __init__(
        self,
        model_path,
        target_position,
        target_rotation,
        target_position_range,

            

Reported by Pylint.

Too many local variables (21/15)
Error

Line: 14 Column: 5

              

class ManipulateTouchSensorsEnv(manipulate.ManipulateEnv):
    def __init__(
        self,
        model_path,
        target_position,
        target_rotation,
        target_position_range,

            

Reported by Pylint.

Line too long (104/100)
Error

Line: 41 Column: 1

                              - "off" or else: does not show touch sensor sites
            touch_get_obs (string): touch sensor readings
                - "boolean": returns 1 if touch sensor reading != 0.0 else 0
                - "sensordata": returns original touch sensor readings from self.sim.data.sensordata[id]
                - "log": returns log(x+1) touch sensor readings from self.sim.data.sensordata[id]
                - "off" or else: does not add touch sensor readings to the observation

        """
        self.touch_visualisation = touch_visualisation

            

Reported by Pylint.

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

Line: 72 Column: 13

              
        for (
            k,
            v,
        ) in (
            self.sim.model._sensor_name2id.items()
        ):  # get touch sensor site names and their ids
            if "robot0:TS_" in k:
                self._touch_sensor_id_site_id.append(

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 109 Column: 9

                      )

    def _render_callback(self):
        super(ManipulateTouchSensorsEnv, self)._render_callback()
        if self.touch_visualisation == "on_touch":
            for touch_sensor_id, site_id in self._touch_sensor_id_site_id:
                if self.sim.data.sensordata[touch_sensor_id] != 0.0:
                    self.sim.model.site_rgba[site_id] = self.touch_color
                else:

            

Reported by Pylint.

Missing class docstring
Error

Line: 141 Column: 1

                      }


class HandBlockTouchSensorsEnv(ManipulateTouchSensorsEnv, utils.EzPickle):
    def __init__(
        self,
        target_position="random",
        target_rotation="xyz",
        touch_get_obs="sensordata",

            

Reported by Pylint.

gym/utils/seeding.py
15 issues
Module 'numpy.random' has no 'RandomState' member
Error

Line: 19 Column: 11

              
    seed = create_seed(seed)

    rng = np.random.RandomState()
    rng.seed(_int_list_from_bigint(hash_seed(seed)))
    return rng, seed


def hash_seed(seed=None, max_bytes=8):

            

Reported by Pylint.

Unused random imported as _random
Error

Line: 4 Column: 1

              import hashlib
import numpy as np
import os
import random as _random
import struct
import sys

from gym import error


            

Reported by Pylint.

Unused import sys
Error

Line: 6 Column: 1

              import os
import random as _random
import struct
import sys

from gym import error


def np_random(seed=None):

            

Reported by Pylint.

Redefining built-in 'hash'
Error

Line: 45 Column: 5

                  """
    if seed is None:
        seed = create_seed(max_bytes=max_bytes)
    hash = hashlib.sha512(str(seed).encode("utf8")).digest()
    return _bigint_from_bytes(hash[:max_bytes])


def create_seed(a=None, max_bytes=8):
    """Create a strong random seed. Otherwise, Python 2 would seed using

            

Reported by Pylint.

TODO: don't hardcode sizeof_int here
Error

Line: 73 Column: 3

                  return a


# TODO: don't hardcode sizeof_int here
def _bigint_from_bytes(bytes):
    sizeof_int = 4
    padding = sizeof_int - len(bytes) % sizeof_int
    bytes += b"\0" * padding
    int_count = int(len(bytes) / sizeof_int)

            

Reported by Pylint.

Redefining built-in 'bytes'
Error

Line: 74 Column: 24

              

# TODO: don't hardcode sizeof_int here
def _bigint_from_bytes(bytes):
    sizeof_int = 4
    padding = sizeof_int - len(bytes) % sizeof_int
    bytes += b"\0" * padding
    int_count = int(len(bytes) / sizeof_int)
    unpacked = struct.unpack("{}I".format(int_count), bytes)

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import hashlib
import numpy as np
import os
import random as _random
import struct
import sys

from gym import error


            

Reported by Pylint.

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

Line: 3 Column: 1

              import hashlib
import numpy as np
import os
import random as _random
import struct
import sys

from gym import error


            

Reported by Pylint.

standard import "import random as _random" should be placed before "import numpy as np"
Error

Line: 4 Column: 1

              import hashlib
import numpy as np
import os
import random as _random
import struct
import sys

from gym import error


            

Reported by Pylint.

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

Line: 5 Column: 1

              import numpy as np
import os
import random as _random
import struct
import sys

from gym import error



            

Reported by Pylint.

gym/spaces/tuple.py
14 issues
Attempted relative import beyond top-level package
Error

Line: 2 Column: 1

              import numpy as np
from .space import Space


class Tuple(Space):
    """
    A tuple (i.e., product) of simpler spaces

    Example usage:

            

Reported by Pylint.

Unused numpy imported as np
Error

Line: 1 Column: 1

              import numpy as np
from .space import Space


class Tuple(Space):
    """
    A tuple (i.e., product) of simpler spaces

    Example usage:

            

Reported by Pylint.

Expression "[space.seed(seed) for space in self.spaces]" is assigned to nothing
Error

Line: 22 Column: 9

                      super(Tuple, self).__init__(None, None)

    def seed(self, seed=None):
        [space.seed(seed) for space in self.spaces]

    def sample(self):
        return tuple([space.sample() for space in self.spaces])

    def contains(self, x):

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np
from .space import Space


class Tuple(Space):
    """
    A tuple (i.e., product) of simpler spaces

    Example usage:

            

Reported by Pylint.

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

                  def __init__(self, spaces):
        self.spaces = spaces
        for space in spaces:
            assert isinstance(
                space, Space
            ), "Elements of the tuple must be instances of gym.Space"
        super(Tuple, self).__init__(None, None)

    def seed(self, seed=None):

            

Reported by Bandit.

Consider using Python 3 style super() without arguments
Error

Line: 19 Column: 9

                          assert isinstance(
                space, Space
            ), "Elements of the tuple must be instances of gym.Space"
        super(Tuple, self).__init__(None, None)

    def seed(self, seed=None):
        [space.seed(seed) for space in self.spaces]

    def sample(self):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 21 Column: 5

                          ), "Elements of the tuple must be instances of gym.Space"
        super(Tuple, self).__init__(None, None)

    def seed(self, seed=None):
        [space.seed(seed) for space in self.spaces]

    def sample(self):
        return tuple([space.sample() for space in self.spaces])


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 24 Column: 5

                  def seed(self, seed=None):
        [space.seed(seed) for space in self.spaces]

    def sample(self):
        return tuple([space.sample() for space in self.spaces])

    def contains(self, x):
        if isinstance(x, list):
            x = tuple(x)  # Promote list to tuple for contains check

            

Reported by Pylint.

Consider using a generator instead 'tuple(space.sample() for space in self.spaces)'
Error

Line: 25 Column: 16

                      [space.seed(seed) for space in self.spaces]

    def sample(self):
        return tuple([space.sample() for space in self.spaces])

    def contains(self, x):
        if isinstance(x, list):
            x = tuple(x)  # Promote list to tuple for contains check
        return (

            

Reported by Pylint.

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

Line: 27 Column: 5

                  def sample(self):
        return tuple([space.sample() for space in self.spaces])

    def contains(self, x):
        if isinstance(x, list):
            x = tuple(x)  # Promote list to tuple for contains check
        return (
            isinstance(x, tuple)
            and len(x) == len(self.spaces)

            

Reported by Pylint.

gym/spaces/dict.py
14 issues
Attempted relative import beyond top-level package
Error

Line: 2 Column: 1

              from collections import OrderedDict
from .space import Space


class Dict(Space):
    """
    A dictionary of simpler spaces.

    Example usage:

            

Reported by Pylint.

Expression "[space.seed(seed) for space in self.spaces.values()]" is assigned to nothing
Error

Line: 55 Column: 9

                      )  # None for shape and dtype, since it'll require special handling

    def seed(self, seed=None):
        [space.seed(seed) for space in self.spaces.values()]

    def sample(self):
        return OrderedDict([(k, space.sample()) for k, space in self.spaces.items()])

    def contains(self, x):

            

Reported by Pylint.

Using possibly undefined loop variable 'key'
Error

Line: 102 Column: 44

                      for key, space in self.spaces.items():
            dict_of_list[key] = space.from_jsonable(sample_n[key])
        ret = []
        for i, _ in enumerate(dict_of_list[key]):
            entry = {}
            for key, value in dict_of_list.items():
                entry[key] = value[i]
            ret.append(entry)
        return ret

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from collections import OrderedDict
from .space import Space


class Dict(Space):
    """
    A dictionary of simpler spaces.

    Example usage:

            

Reported by Pylint.

Line too long (106/100)
Error

Line: 10 Column: 1

                  A dictionary of simpler spaces.

    Example usage:
    self.observation_space = spaces.Dict({"position": spaces.Discrete(2), "velocity": spaces.Discrete(3)})

    Example usage [nested]:
    self.nested_observation_space = spaces.Dict({
        'sensors':  spaces.Dict({
            'position': spaces.Box(low=-100, high=100, shape=(3,)),

            

Reported by Pylint.

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

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

                  """

    def __init__(self, spaces=None, **spaces_kwargs):
        assert (spaces is None) or (
            not spaces_kwargs
        ), "Use either Dict(spaces=dict(...)) or Dict(foo=x, bar=z)"
        if spaces is None:
            spaces = spaces_kwargs
        if isinstance(spaces, dict) and not isinstance(spaces, OrderedDict):

            

Reported by Bandit.

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

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

                          spaces = OrderedDict(spaces)
        self.spaces = spaces
        for space in spaces.values():
            assert isinstance(
                space, Space
            ), "Values of the dict should be instances of gym.Space"
        super(Dict, self).__init__(
            None, None
        )  # None for shape and dtype, since it'll require special handling

            

Reported by Bandit.

Consider using Python 3 style super() without arguments
Error

Line: 50 Column: 9

                          assert isinstance(
                space, Space
            ), "Values of the dict should be instances of gym.Space"
        super(Dict, self).__init__(
            None, None
        )  # None for shape and dtype, since it'll require special handling

    def seed(self, seed=None):
        [space.seed(seed) for space in self.spaces.values()]

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 54 Column: 5

                          None, None
        )  # None for shape and dtype, since it'll require special handling

    def seed(self, seed=None):
        [space.seed(seed) for space in self.spaces.values()]

    def sample(self):
        return OrderedDict([(k, space.sample()) for k, space in self.spaces.items()])


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 57 Column: 5

                  def seed(self, seed=None):
        [space.seed(seed) for space in self.spaces.values()]

    def sample(self):
        return OrderedDict([(k, space.sample()) for k, space in self.spaces.items()])

    def contains(self, x):
        if not isinstance(x, dict) or len(x) != len(self.spaces):
            return False

            

Reported by Pylint.

gym/utils/tests/test_env_checker.py
14 issues
Unable to import 'gym'
Error

Line: 1 Column: 1

              import gym
import numpy as np
import pytest
from gym.spaces import Box, Dict, Discrete

from gym.utils.env_checker import check_env


class ActionDictTestEnv(gym.Env):

            

Reported by Pylint.

Unable to import 'pytest'
Error

Line: 3 Column: 1

              import gym
import numpy as np
import pytest
from gym.spaces import Box, Dict, Discrete

from gym.utils.env_checker import check_env


class ActionDictTestEnv(gym.Env):

            

Reported by Pylint.

Unable to import 'gym.spaces'
Error

Line: 4 Column: 1

              import gym
import numpy as np
import pytest
from gym.spaces import Box, Dict, Discrete

from gym.utils.env_checker import check_env


class ActionDictTestEnv(gym.Env):

            

Reported by Pylint.

Unable to import 'gym.utils.env_checker'
Error

Line: 6 Column: 1

              import pytest
from gym.spaces import Box, Dict, Discrete

from gym.utils.env_checker import check_env


class ActionDictTestEnv(gym.Env):
    action_space = Dict({"position": Discrete(1), "velocity": Discrete(1)})
    observation_space = Box(low=-1.0, high=2.0, shape=(3,), dtype=np.float32)

            

Reported by Pylint.

Unused argument 'action'
Error

Line: 13 Column: 20

                  action_space = Dict({"position": Discrete(1), "velocity": Discrete(1)})
    observation_space = Box(low=-1.0, high=2.0, shape=(3,), dtype=np.float32)

    def step(self, action):
        observation = np.array([1.0, 1.5, 0.5])
        reward = 1
        done = True
        return observation, reward, done


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import gym
import numpy as np
import pytest
from gym.spaces import Box, Dict, Discrete

from gym.utils.env_checker import check_env


class ActionDictTestEnv(gym.Env):

            

Reported by Pylint.

Missing class docstring
Error

Line: 9 Column: 1

              from gym.utils.env_checker import check_env


class ActionDictTestEnv(gym.Env):
    action_space = Dict({"position": Discrete(1), "velocity": Discrete(1)})
    observation_space = Box(low=-1.0, high=2.0, shape=(3,), dtype=np.float32)

    def step(self, action):
        observation = np.array([1.0, 1.5, 0.5])

            

Reported by Pylint.

Method could be a function
Error

Line: 13 Column: 5

                  action_space = Dict({"position": Discrete(1), "velocity": Discrete(1)})
    observation_space = Box(low=-1.0, high=2.0, shape=(3,), dtype=np.float32)

    def step(self, action):
        observation = np.array([1.0, 1.5, 0.5])
        reward = 1
        done = True
        return observation, reward, done


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 13 Column: 5

                  action_space = Dict({"position": Discrete(1), "velocity": Discrete(1)})
    observation_space = Box(low=-1.0, high=2.0, shape=(3,), dtype=np.float32)

    def step(self, action):
        observation = np.array([1.0, 1.5, 0.5])
        reward = 1
        done = True
        return observation, reward, done


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 19 Column: 5

                      done = True
        return observation, reward, done

    def reset(self):
        return np.array([1.0, 1.5, 0.5])

    def render(self, mode="human"):
        pass


            

Reported by Pylint.

gym/wrappers/test_frame_stack.py
14 issues
Unable to import 'pytest'
Error

Line: 1 Column: 1

              import pytest

pytest.importorskip("atari_py")

import numpy as np
import gym
from gym.wrappers import FrameStack

try:

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import pytest

pytest.importorskip("atari_py")

import numpy as np
import gym
from gym.wrappers import FrameStack

try:

            

Reported by Pylint.

Import "import numpy as np" should be placed at the top of the module
Error

Line: 5 Column: 1

              
pytest.importorskip("atari_py")

import numpy as np
import gym
from gym.wrappers import FrameStack

try:
    import lz4

            

Reported by Pylint.

Import "import gym" should be placed at the top of the module
Error

Line: 6 Column: 1

              pytest.importorskip("atari_py")

import numpy as np
import gym
from gym.wrappers import FrameStack

try:
    import lz4
except ImportError:

            

Reported by Pylint.

Import "from gym.wrappers import FrameStack" should be placed at the top of the module
Error

Line: 7 Column: 1

              
import numpy as np
import gym
from gym.wrappers import FrameStack

try:
    import lz4
except ImportError:
    lz4 = None

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 27 Column: 1

                          ),
        ),
        False,
    ],
)
def test_frame_stack(env_id, num_stack, lz4_compress):
    env = gym.make(env_id)
    shape = env.observation_space.shape
    env = FrameStack(env, num_stack, lz4_compress)

            

Reported by Pylint.

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

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

                  env = gym.make(env_id)
    shape = env.observation_space.shape
    env = FrameStack(env, num_stack, lz4_compress)
    assert env.observation_space.shape == (num_stack,) + shape
    assert env.observation_space.dtype == env.env.observation_space.dtype

    obs = env.reset()
    obs = np.asarray(obs)
    assert obs.shape == (num_stack,) + shape

            

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

                  shape = env.observation_space.shape
    env = FrameStack(env, num_stack, lz4_compress)
    assert env.observation_space.shape == (num_stack,) + shape
    assert env.observation_space.dtype == env.env.observation_space.dtype

    obs = env.reset()
    obs = np.asarray(obs)
    assert obs.shape == (num_stack,) + shape
    for i in range(1, num_stack):

            

Reported by Bandit.

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

              
    obs = env.reset()
    obs = np.asarray(obs)
    assert obs.shape == (num_stack,) + shape
    for i in range(1, num_stack):
        assert np.allclose(obs[i - 1], obs[i])

    obs, _, _, _ = env.step(env.action_space.sample())
    obs = np.asarray(obs)

            

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

                  obs = np.asarray(obs)
    assert obs.shape == (num_stack,) + shape
    for i in range(1, num_stack):
        assert np.allclose(obs[i - 1], obs[i])

    obs, _, _, _ = env.step(env.action_space.sample())
    obs = np.asarray(obs)
    assert obs.shape == (num_stack,) + shape
    for i in range(1, num_stack - 1):

            

Reported by Bandit.