The following issues were found

tests/gym/envs/robotics/hand/test_manipulate.py
7 issues
Unable to import 'pytest'
Error

Line: 4 Column: 1

              import pickle
import unittest

import pytest

from gym import envs
from gym.envs.tests.spec_list import skip_mujoco, SKIP_MUJOCO_WARNING_MESSAGE



            

Reported by Pylint.

Unused import unittest
Error

Line: 2 Column: 1

              import pickle
import unittest

import pytest

from gym import envs
from gym.envs.tests.spec_list import skip_mujoco, SKIP_MUJOCO_WARNING_MESSAGE



            

Reported by Pylint.

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

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

              def test_serialize_deserialize(environment_id):
    env1 = envs.make(environment_id, target_position="fixed")
    env1.reset()
    env2 = pickle.loads(pickle.dumps(env1))

    assert env1.target_position == env2.target_position, (
        env1.target_position,
        env2.target_position,
    )

            

Reported by Bandit.

Missing module docstring
Error

Line: 1 Column: 1

              import pickle
import unittest

import pytest

from gym import envs
from gym.envs.tests.spec_list import skip_mujoco, SKIP_MUJOCO_WARNING_MESSAGE



            

Reported by Pylint.

Consider possible security implications associated with pickle module.
Security blacklist

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

              import pickle
import unittest

import pytest

from gym import envs
from gym.envs.tests.spec_list import skip_mujoco, SKIP_MUJOCO_WARNING_MESSAGE



            

Reported by Bandit.

Missing function or method docstring
Error

Line: 19 Column: 1

              
@pytest.mark.skipif(skip_mujoco, reason=SKIP_MUJOCO_WARNING_MESSAGE)
@pytest.mark.parametrize("environment_id", ENVIRONMENT_IDS)
def test_serialize_deserialize(environment_id):
    env1 = envs.make(environment_id, target_position="fixed")
    env1.reset()
    env2 = pickle.loads(pickle.dumps(env1))

    assert env1.target_position == env2.target_position, (

            

Reported by Pylint.

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

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

                  env1.reset()
    env2 = pickle.loads(pickle.dumps(env1))

    assert env1.target_position == env2.target_position, (
        env1.target_position,
        env2.target_position,
    )

            

Reported by Bandit.

gym/vector/tests/test_spaces.py
7 issues
Unable to import 'pytest'
Error

Line: 1 Column: 1

              import pytest
import numpy as np

from gym.spaces import Box, MultiDiscrete, Tuple, Dict
from gym.vector.tests.utils import spaces, custom_spaces, CustomSpace

from gym.vector.utils.spaces import _BaseGymSpaces, batch_space

expected_batch_spaces_4 = [

            

Reported by Pylint.

Unused _BaseGymSpaces imported from gym.vector.utils.spaces
Error

Line: 7 Column: 1

              from gym.spaces import Box, MultiDiscrete, Tuple, Dict
from gym.vector.tests.utils import spaces, custom_spaces, CustomSpace

from gym.vector.utils.spaces import _BaseGymSpaces, batch_space

expected_batch_spaces_4 = [
    Box(low=-1.0, high=1.0, shape=(4,), dtype=np.float64),
    Box(low=0.0, high=10.0, shape=(4, 1), dtype=np.float32),
    Box(

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import pytest
import numpy as np

from gym.spaces import Box, MultiDiscrete, Tuple, Dict
from gym.vector.tests.utils import spaces, custom_spaces, CustomSpace

from gym.vector.utils.spaces import _BaseGymSpaces, batch_space

expected_batch_spaces_4 = [

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 92 Column: 1

                  "space,expected_batch_space_4",
    list(zip(spaces, expected_batch_spaces_4)),
    ids=[space.__class__.__name__ for space in spaces],
)
def test_batch_space(space, expected_batch_space_4):
    batch_space_4 = batch_space(space, n=4)
    assert batch_space_4 == expected_batch_space_4



            

Reported by Pylint.

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

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

              )
def test_batch_space(space, expected_batch_space_4):
    batch_space_4 = batch_space(space, n=4)
    assert batch_space_4 == expected_batch_space_4


@pytest.mark.parametrize(
    "space,expected_batch_space_4",
    list(zip(custom_spaces, expected_custom_batch_spaces_4)),

            

Reported by Bandit.

Missing function or method docstring
Error

Line: 102 Column: 1

                  "space,expected_batch_space_4",
    list(zip(custom_spaces, expected_custom_batch_spaces_4)),
    ids=[space.__class__.__name__ for space in custom_spaces],
)
def test_batch_space_custom_space(space, expected_batch_space_4):
    batch_space_4 = batch_space(space, n=4)
    assert batch_space_4 == expected_batch_space_4

            

Reported by Pylint.

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

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

              )
def test_batch_space_custom_space(space, expected_batch_space_4):
    batch_space_4 = batch_space(space, n=4)
    assert batch_space_4 == expected_batch_space_4

            

Reported by Bandit.

gym/spaces/space.py
7 issues
Missing module docstring
Error

Line: 1 Column: 1

              from gym.utils import seeding


class Space(object):
    """Defines the observation and action spaces, so you can write generic
    code that applies to any Env. For example, you can choose a random
    action.

    WARNING - Custom observation & action spaces can inherit from the `Space`

            

Reported by Pylint.

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

Line: 4 Column: 1

              from gym.utils import seeding


class Space(object):
    """Defines the observation and action spaces, so you can write generic
    code that applies to any Env. For example, you can choose a random
    action.

    WARNING - Custom observation & action spaces can inherit from the `Space`

            

Reported by Pylint.

Import outside toplevel (numpy)
Error

Line: 20 Column: 9

                  """

    def __init__(self, shape=None, dtype=None):
        import numpy as np  # takes about 300-400ms to import, so we load lazily

        self.shape = None if shape is None else tuple(shape)
        self.dtype = None if dtype is None else np.dtype(dtype)
        self._np_random = None


            

Reported by Pylint.

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

Line: 46 Column: 5

                      self._np_random, seed = seeding.np_random(seed)
        return [seed]

    def contains(self, x):
        """
        Return boolean specifying if x is a valid
        member of this space
        """
        raise NotImplementedError

            

Reported by Pylint.

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

Line: 53 Column: 5

                      """
        raise NotImplementedError

    def __contains__(self, x):
        return self.contains(x)

    def to_jsonable(self, sample_n):
        """Convert a batch of samples from this space to a JSONable data type."""
        # By default, assume identity is JSONable

            

Reported by Pylint.

Method could be a function
Error

Line: 56 Column: 5

                  def __contains__(self, x):
        return self.contains(x)

    def to_jsonable(self, sample_n):
        """Convert a batch of samples from this space to a JSONable data type."""
        # By default, assume identity is JSONable
        return sample_n

    def from_jsonable(self, sample_n):

            

Reported by Pylint.

Method could be a function
Error

Line: 61 Column: 5

                      # By default, assume identity is JSONable
        return sample_n

    def from_jsonable(self, sample_n):
        """Convert a JSONable data type to a batch of samples from this space."""
        # By default, assume identity is JSONable
        return sample_n

            

Reported by Pylint.

gym/tests/test_core.py
7 issues
Unable to import 'gym'
Error

Line: 1 Column: 1

              from gym import core


class ArgumentEnv(core.Env):
    calls = 0

    def __init__(self, arg):
        self.calls += 1
        self.arg = arg

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from gym import core


class ArgumentEnv(core.Env):
    calls = 0

    def __init__(self, arg):
        self.calls += 1
        self.arg = arg

            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 4 Column: 1

              from gym import core


class ArgumentEnv(core.Env):
    calls = 0

    def __init__(self, arg):
        self.calls += 1
        self.arg = arg

            

Reported by Pylint.

Missing class docstring
Error

Line: 4 Column: 1

              from gym import core


class ArgumentEnv(core.Env):
    calls = 0

    def __init__(self, arg):
        self.calls += 1
        self.arg = arg

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 12 Column: 1

                      self.arg = arg


def test_env_instantiation():
    # This looks like a pretty trivial, but given our usage of
    # __new__, it's worth having.
    env = ArgumentEnv("arg")
    assert env.arg == "arg"
    assert env.calls == 1

            

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

                  # This looks like a pretty trivial, but given our usage of
    # __new__, it's worth having.
    env = ArgumentEnv("arg")
    assert env.arg == "arg"
    assert env.calls == 1

            

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

                  # __new__, it's worth having.
    env = ArgumentEnv("arg")
    assert env.arg == "arg"
    assert env.calls == 1

            

Reported by Bandit.

gym/vector/tests/test_vector_env_wrapper.py
7 issues
Unused import gym
Error

Line: 1 Column: 1

              import gym
from gym.vector import make
from gym.vector import VectorEnvWrapper


class DummyWrapper(VectorEnvWrapper):
    def __init__(self, env):
        self.env = env
        self.counter = 0

            

Reported by Pylint.

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

Line: 6 Column: 1

              from gym.vector import VectorEnvWrapper


class DummyWrapper(VectorEnvWrapper):
    def __init__(self, env):
        self.env = env
        self.counter = 0

    def reset_async(self):

            

Reported by Pylint.

__init__ method from base class 'VectorEnvWrapper' is not called
Error

Line: 7 Column: 5

              

class DummyWrapper(VectorEnvWrapper):
    def __init__(self, env):
        self.env = env
        self.counter = 0

    def reset_async(self):
        super().reset_async()

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import gym
from gym.vector import make
from gym.vector import VectorEnvWrapper


class DummyWrapper(VectorEnvWrapper):
    def __init__(self, env):
        self.env = env
        self.counter = 0

            

Reported by Pylint.

Missing class docstring
Error

Line: 6 Column: 1

              from gym.vector import VectorEnvWrapper


class DummyWrapper(VectorEnvWrapper):
    def __init__(self, env):
        self.env = env
        self.counter = 0

    def reset_async(self):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 16 Column: 1

                      self.counter += 1


def test_vector_env_wrapper_inheritance():
    env = make("FrozenLake-v1", asynchronous=False)
    wrapped = DummyWrapper(env)
    wrapped.reset()
    assert wrapped.counter == 1

            

Reported by Pylint.

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

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

                  env = make("FrozenLake-v1", asynchronous=False)
    wrapped = DummyWrapper(env)
    wrapped.reset()
    assert wrapped.counter == 1

            

Reported by Bandit.

gym/spaces/utils.py
6 issues
Missing module docstring
Error

Line: 1 Column: 1

              from collections import OrderedDict
import numpy as np

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

            

Reported by Pylint.

Unnecessary "elif" after "return"
Error

Line: 19 Column: 5

                  Accepts a space and returns an integer. Raises ``NotImplementedError`` if
    the space is not defined in ``gym.spaces``.
    """
    if isinstance(space, Box):
        return int(np.prod(space.shape))
    elif isinstance(space, Discrete):
        return int(space.n)
    elif isinstance(space, Tuple):
        return int(sum([flatdim(s) for s in space.spaces]))

            

Reported by Pylint.

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

Line: 35 Column: 1

                      raise NotImplementedError


def flatten(space, x):
    """Flatten a data point from a space.

    This is useful when e.g. points from spaces must be passed to a neural
    network, which only understands flat arrays of floats.


            

Reported by Pylint.

Unnecessary "elif" after "return"
Error

Line: 45 Column: 5

                  Raises ``NotImplementedError`` if the space is not defined in
    ``gym.spaces``.
    """
    if isinstance(space, Box):
        return np.asarray(x, dtype=space.dtype).flatten()
    elif isinstance(space, Discrete):
        onehot = np.zeros(space.n, dtype=space.dtype)
        onehot[x] = 1
        return onehot

            

Reported by Pylint.

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

Line: 65 Column: 1

                      raise NotImplementedError


def unflatten(space, x):
    """Unflatten a data point from a space.

    This reverses the transformation applied by ``flatten()``. You must ensure
    that the ``space`` argument is the same as for the ``flatten()`` call.


            

Reported by Pylint.

Unnecessary "elif" after "return"
Error

Line: 75 Column: 5

                  that matches the space. Raises ``NotImplementedError`` if the space is not
    defined in ``gym.spaces``.
    """
    if isinstance(space, Box):
        return np.asarray(x, dtype=space.dtype).reshape(space.shape)
    elif isinstance(space, Discrete):
        return int(np.nonzero(x)[0][0])
    elif isinstance(space, Tuple):
        dims = [flatdim(s) for s in space.spaces]

            

Reported by Pylint.

gym/logger.py
6 issues
Using the global statement
Error

Line: 18 Column: 5

                  """
    Set logging threshold on current logger.
    """
    global MIN_LEVEL
    MIN_LEVEL = level


def debug(msg, *args):
    if MIN_LEVEL <= DEBUG:

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import warnings

from gym.utils import colorize

DEBUG = 10
INFO = 20
WARN = 30
ERROR = 40
DISABLED = 50

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 22 Column: 1

                  MIN_LEVEL = level


def debug(msg, *args):
    if MIN_LEVEL <= DEBUG:
        print("%s: %s" % ("DEBUG", msg % args))


def info(msg, *args):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 27 Column: 1

                      print("%s: %s" % ("DEBUG", msg % args))


def info(msg, *args):
    if MIN_LEVEL <= INFO:
        print("%s: %s" % ("INFO", msg % args))


def warn(msg, *args):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 32 Column: 1

                      print("%s: %s" % ("INFO", msg % args))


def warn(msg, *args):
    if MIN_LEVEL <= WARN:
        warnings.warn(colorize("%s: %s" % ("WARN", msg % args), "yellow"))


def error(msg, *args):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 37 Column: 1

                      warnings.warn(colorize("%s: %s" % ("WARN", msg % args), "yellow"))


def error(msg, *args):
    if MIN_LEVEL <= ERROR:
        print(colorize("%s: %s" % ("ERROR", msg % args), "red"))


# DEPRECATED:

            

Reported by Pylint.

gym/wrappers/test_rescale_action.py
6 issues
Unable to import 'pytest'
Error

Line: 1 Column: 1

              import pytest

import numpy as np

import gym
from gym.wrappers import RescaleAction


def test_rescale_action():

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import pytest

import numpy as np

import gym
from gym.wrappers import RescaleAction


def test_rescale_action():

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 9 Column: 1

              from gym.wrappers import RescaleAction


def test_rescale_action():
    env = gym.make("CartPole-v1")
    with pytest.raises(AssertionError):
        env = RescaleAction(env, -1, 1)
    del env


            

Reported by Pylint.

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

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

              
    obs = env.reset()
    wrapped_obs = wrapped_env.reset()
    assert np.allclose(obs, wrapped_obs)

    obs, reward, _, _ = env.step([1.5])
    with pytest.raises(AssertionError):
        wrapped_env.step([1.5])
    wrapped_obs, wrapped_reward, _, _ = wrapped_env.step([0.75])

            

Reported by Bandit.

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

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

                      wrapped_env.step([1.5])
    wrapped_obs, wrapped_reward, _, _ = wrapped_env.step([0.75])

    assert np.allclose(obs, wrapped_obs)
    assert np.allclose(reward, wrapped_reward)

            

Reported by Bandit.

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

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

                  wrapped_obs, wrapped_reward, _, _ = wrapped_env.step([0.75])

    assert np.allclose(obs, wrapped_obs)
    assert np.allclose(reward, wrapped_reward)

            

Reported by Bandit.

gym/envs/robotics/utils.py
6 issues
Possible unbalanced tuple unpacking with sequence defined at line 785 of numpy.lib.shape_base: left side has 2 label(s), right side has 0 value(s)
Error

Line: 33 Column: 9

                  For position actuators it sets the target relative to the current qpos.
    """
    if sim.model.nmocap > 0:
        _, action = np.split(action, (sim.model.nmocap * 7,))
    if sim.data.ctrl is not None:
        for i in range(action.shape[0]):
            if sim.model.actuator_biastype[i] == 0:
                sim.data.ctrl[i] = action[i]
            else:

            

Reported by Pylint.

Possible unbalanced tuple unpacking with sequence defined at line 785 of numpy.lib.shape_base: left side has 2 label(s), right side has 0 value(s)
Error

Line: 53 Column: 9

                  constraint optimizer tries to center the welded body on the mocap.
    """
    if sim.model.nmocap > 0:
        action, _ = np.split(action, (sim.model.nmocap * 7,))
        action = action.reshape(sim.model.nmocap, 7)

        pos_delta = action[:, :3]
        quat_delta = action[:, 3:]


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import numpy as np

from gym import error

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(

            

Reported by Pylint.

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

Line: 7 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: 9 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
        )
    )



            

Reported by Pylint.

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

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

                          mocap_id = sim.model.body_mocapid[obj2_id]
            body_idx = obj1_id

        assert mocap_id != -1
        sim.data.mocap_pos[mocap_id][:] = sim.data.body_xpos[body_idx]
        sim.data.mocap_quat[mocap_id][:] = sim.data.body_xquat[body_idx]

            

Reported by Bandit.

tests/gym/envs/robotics/hand/test_reach.py
6 issues
Unable to import 'pytest'
Error

Line: 3 Column: 1

              import pickle

import pytest

from gym import envs
from gym.envs.tests.spec_list import skip_mujoco, SKIP_MUJOCO_WARNING_MESSAGE


@pytest.mark.skipif(skip_mujoco, reason=SKIP_MUJOCO_WARNING_MESSAGE)

            

Reported by Pylint.

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

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

              def test_serialize_deserialize():
    env1 = envs.make("HandReach-v0", distance_threshold=1e-6)
    env1.reset()
    env2 = pickle.loads(pickle.dumps(env1))

    assert env1.distance_threshold == env2.distance_threshold, (
        env1.distance_threshold,
        env2.distance_threshold,
    )

            

Reported by Bandit.

Missing module docstring
Error

Line: 1 Column: 1

              import pickle

import pytest

from gym import envs
from gym.envs.tests.spec_list import skip_mujoco, SKIP_MUJOCO_WARNING_MESSAGE


@pytest.mark.skipif(skip_mujoco, reason=SKIP_MUJOCO_WARNING_MESSAGE)

            

Reported by Pylint.

Consider possible security implications associated with pickle module.
Security blacklist

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

              import pickle

import pytest

from gym import envs
from gym.envs.tests.spec_list import skip_mujoco, SKIP_MUJOCO_WARNING_MESSAGE


@pytest.mark.skipif(skip_mujoco, reason=SKIP_MUJOCO_WARNING_MESSAGE)

            

Reported by Bandit.

Missing function or method docstring
Error

Line: 10 Column: 1

              

@pytest.mark.skipif(skip_mujoco, reason=SKIP_MUJOCO_WARNING_MESSAGE)
def test_serialize_deserialize():
    env1 = envs.make("HandReach-v0", distance_threshold=1e-6)
    env1.reset()
    env2 = pickle.loads(pickle.dumps(env1))

    assert env1.distance_threshold == env2.distance_threshold, (

            

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

                  env1.reset()
    env2 = pickle.loads(pickle.dumps(env1))

    assert env1.distance_threshold == env2.distance_threshold, (
        env1.distance_threshold,
        env2.distance_threshold,
    )

            

Reported by Bandit.