Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Farama Foundation Gymnasium TimeLimit Wrapper

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

Overview

Concrete tool for enforcing maximum episode step limits via truncation provided by the Gymnasium library.

Description

The TimeLimit wrapper counts steps within each episode and sets truncated=True when the count reaches max_episode_steps. It resets the counter on each reset() call. This wrapper is automatically applied by gymnasium.make() when max_episode_steps is specified in the EnvSpec.

Usage

Typically applied automatically by gymnasium.make(). Apply manually when creating environments directly (not via make()) and you need episode length limits.

Code Reference

Source Location

  • Repository: Gymnasium
  • File: gymnasium/wrappers/common.py
  • Lines: L42-165

Signature

class TimeLimit(gym.Wrapper[ObsType, ActType, ObsType, ActType]):
    def __init__(
        self,
        env: gym.Env,
        max_episode_steps: int,
    ):
        """Limits the number of steps for an environment.

        Args:
            env: The environment to apply the wrapper
            max_episode_steps: Steps after which the episode is truncated
        """

Import

from gymnasium.wrappers import TimeLimit

I/O Contract

Inputs

Name Type Required Description
env gym.Env Yes Environment to wrap
max_episode_steps int Yes Maximum steps before truncation (must be > 0)

Outputs

Name Type Description
step() tuple Standard 5-tuple with truncated=True when step limit reached

Usage Examples

Manual Application

from gymnasium.wrappers import TimeLimit
from gymnasium.envs.classic_control import CartPoleEnv

# Create unwrapped environment
env = CartPoleEnv()

# Apply time limit
env = TimeLimit(env, max_episode_steps=100)

obs, info = env.reset(seed=42)
for step in range(200):
    obs, reward, terminated, truncated, info = env.step(env.action_space.sample())
    if truncated:
        print(f"Truncated at step {step + 1}")  # Truncated at step 100
        break
env.close()

Related Pages

Implements Principle

Requires Environment

Page Connections

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