Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Farama Foundation Gymnasium Space Base

From Leeroopedia
Knowledge Sources
Domains Reinforcement_Learning, Spaces
Last Updated 2026-02-15 03:00 GMT

Overview

Concrete tool for defining the abstract base class of all observation and action spaces provided by Gymnasium.

Description

The Space class is the abstract superclass for all Gymnasium spaces. It defines the interface that every space must implement, including sampling, membership testing, seeding, and JSON serialization. All built-in spaces (Box, Discrete, MultiBinary, MultiDiscrete, Tuple, Dict, Graph, Text, Sequence, OneOf) inherit from this class.

The class is generic over a covariant type variable T_cov, allowing type-safe definitions like Space[NDArray[np.int8]] for MultiBinary or Space[str] for Text.

Key responsibilities of the base class:

  • Shape and dtype management: Stores the shape and numpy dtype of elements, both of which may be None for spaces with dynamic or non-array elements.
  • PRNG management: Provides lazy initialization of a np.random.Generator via the np_random property and seed() method, using Gymnasium's seeding.np_random() utility.
  • Abstract interface: Declares sample(), contains(), and is_np_flattenable as methods that subclasses must implement.
  • Pickle support: Implements __setstate__ for backward-compatible deserialization of legacy pickled states.
  • JSON serialization: Provides default identity-based to_jsonable() and from_jsonable() methods, which subclasses typically override.

Usage

Use Space as the base class when creating custom observation or action spaces. For most use cases, one of the built-in concrete space types (Box, Discrete, etc.) should be used directly. Custom spaces are supported but may not work with all RL algorithm implementations or vector environment wrappers.

Code Reference

Source Location

Signature

class Space(Generic[T_cov]):
    def __init__(
        self,
        shape: Sequence[int] | None = None,
        dtype: npt.DTypeLike | None = None,
        seed: int | np.random.Generator | None = None,
    )

Import

from gymnasium.spaces import Space

I/O Contract

Inputs

Name Type Required Description
shape Sequence[int] or None No The shape of elements in this space. None for spaces with dynamic or non-array elements (e.g., Graph, Sequence, Text).
dtype npt.DTypeLike or None No The numpy dtype of elements. None for non-array spaces.
seed int, np.random.Generator, or None No Optional seed for the PRNG. If a Generator is passed, it is used directly; if an int, the seed() method is called.

Outputs

Name Type Description
sample() returns T_cov A randomly sampled element from this space. Must be implemented by subclasses.
contains() returns bool Whether a given value is a valid member of this space. Must be implemented by subclasses.

Key Properties and Methods

Member Type Description
shape None Returns the shape of the space as an immutable tuple or None.
dtype None The numpy dtype of the space elements.
np_random property -> np.random.Generator Lazily initialized PRNG. Seeds itself on first access if not already seeded.
is_np_flattenable property -> bool Whether this space can be flattened to a Box. Must be implemented by subclasses.
seed(seed=None) list[int] | dict[str, int] Seed the PRNG. Returns the seed value used. Composite spaces may return structured seeds.
sample(mask=None, probability=None) method -> T_cov Randomly sample an element. Supports mask and probability-based sampling.
contains(x) method -> bool Check membership. Also exposed via __contains__ (i.e., x in space).
to_jsonable(sample_n) method -> list[Any] Convert a batch of samples to JSON-serializable format. Default: identity.
from_jsonable(sample_n) method -> list[T_cov] Convert JSON-serializable data back to samples. Default: identity.

Type Aliases

MaskNDArray: TypeAlias = npt.NDArray[np.int8]

The MaskNDArray type alias is defined in this module and used across all space implementations for mask-based sampling.

Usage Examples

from gymnasium.spaces import Space, Box, Discrete

# Typically you use concrete subclasses, not Space directly
box = Box(0, 1, shape=(3,))
print(box.shape)          # (3,)
print(box.dtype)          # float32
print(box.is_np_flattenable)  # True

# The `in` operator uses contains()
sample = box.sample()
print(sample in box)      # True

# Seeding for reproducibility
box.seed(42)
s1 = box.sample()
box.seed(42)
s2 = box.sample()
print((s1 == s2).all())   # True

# JSON round-trip
samples = [box.sample() for _ in range(3)]
jsonable = box.to_jsonable(samples)
recovered = box.from_jsonable(jsonable)

# Custom space (minimal example)
class MySpace(Space):
    @property
    def is_np_flattenable(self):
        return False

    def sample(self, mask=None, probability=None):
        return self.np_random.random()

    def contains(self, x):
        return isinstance(x, float) and 0 <= x <= 1

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment