0
# Environment Registration
1
2
The registration system manages environment discovery and instantiation through string IDs. It provides a global registry where environments can be registered and created by name, enabling consistent environment access across different codebases.
3
4
## Capabilities
5
6
### Environment Creation
7
8
Functions for creating environment instances from registered IDs.
9
10
```python { .api }
11
def make(id: str | EnvSpec, max_episode_steps: int | None = None,
12
disable_env_checker: bool | None = None, **kwargs) -> Env:
13
"""
14
Create an environment instance from a registered ID.
15
16
Args:
17
id: Environment ID (e.g., 'CartPole-v1') or EnvSpec instance
18
max_episode_steps: Override max episode steps (use -1 to disable TimeLimit)
19
disable_env_checker: Whether to disable environment checker
20
**kwargs: Additional arguments passed to environment constructor
21
22
Returns:
23
Environment instance
24
25
Raises:
26
UnregisteredEnv: If environment ID is not registered
27
DependencyNotInstalled: If required dependencies are missing
28
"""
29
30
def make_vec(id: str | EnvSpec, num_envs: int = 1,
31
vectorization_mode: VectorizeMode | str | None = None,
32
vector_kwargs: dict[str, Any] | None = None,
33
wrappers: Sequence[Callable[[Env], Wrapper]] | None = None,
34
**kwargs) -> VectorEnv:
35
"""
36
Create a vectorized environment instance.
37
38
Args:
39
id: Environment ID to vectorize or EnvSpec instance
40
num_envs: Number of parallel environments (default: 1)
41
vectorization_mode: VectorizeMode.SYNC or VectorizeMode.ASYNC
42
vector_kwargs: Additional arguments for vector environment
43
wrappers: Sequence of wrapper functions to apply
44
**kwargs: Additional arguments passed to environment constructor
45
46
Returns:
47
Vectorized environment instance
48
"""
49
```
50
51
### Environment Registration
52
53
Functions for registering new environments with the global registry.
54
55
```python { .api }
56
def register(id: str, entry_point: EnvCreator | str | None = None,
57
reward_threshold: float | None = None, nondeterministic: bool = False,
58
max_episode_steps: int | None = None, order_enforce: bool = True,
59
disable_env_checker: bool = False,
60
additional_wrappers: tuple[WrapperSpec, ...] = (),
61
vector_entry_point: VectorEnvCreator | str | None = None,
62
kwargs: dict | None = None) -> None:
63
"""
64
Register a new environment with the global registry.
65
66
Args:
67
id: Unique environment ID (e.g., 'MyEnv-v0')
68
entry_point: Import path to environment class or callable creating the environment
69
reward_threshold: Reward threshold for completing the environment
70
nondeterministic: Whether environment is nondeterministic
71
max_episode_steps: Maximum steps per episode before truncation
72
order_enforce: Whether to enforce reset before step order
73
disable_env_checker: Whether to disable environment checker
74
additional_wrappers: Tuple of wrapper specs to apply
75
vector_entry_point: Entry point for vectorized environment
76
kwargs: Additional keyword arguments for environment
77
"""
78
79
def register_envs(env_module: ModuleType) -> None:
80
"""
81
No-op function for IDE compatibility when importing modules.
82
83
Args:
84
env_module: Module containing environment registrations
85
"""
86
```
87
88
### Registry Inspection
89
90
Functions for exploring registered environments.
91
92
```python { .api }
93
def spec(id: str) -> EnvSpec:
94
"""
95
Get the specification for a registered environment.
96
97
Args:
98
id: Environment ID
99
100
Returns:
101
Environment specification object
102
103
Raises:
104
UnregisteredEnv: If environment ID is not registered
105
"""
106
107
def pprint_registry(print_registry: dict[str, EnvSpec] = registry, *,
108
num_cols: int = 3, exclude_namespaces: list[str] | None = None,
109
disable_print: bool = False) -> str | None:
110
"""
111
Pretty print all registered environments.
112
113
Args:
114
print_registry: Environment registry to print (default: global registry)
115
num_cols: Number of columns for display
116
exclude_namespaces: Namespaces to exclude from output
117
disable_print: If True, return string instead of printing
118
119
Returns:
120
Formatted string if disable_print=True, otherwise None
121
"""
122
123
registry: dict[str, EnvSpec]
124
"""Global environment registry dictionary mapping IDs to specs."""
125
```
126
127
### Specification Classes
128
129
Classes that define environment and wrapper specifications.
130
131
```python { .api }
132
class EnvSpec:
133
"""
134
Environment specification containing registration metadata.
135
136
Attributes:
137
id: Environment ID
138
entry_point: Import path to environment class or callable
139
reward_threshold: Reward threshold for considering environment solved
140
nondeterministic: Whether environment is nondeterministic
141
max_episode_steps: Maximum steps per episode
142
order_enforce: Whether to enforce reset before step order
143
disable_env_checker: Whether to disable environment checker
144
kwargs: Additional keyword arguments for environment
145
namespace: Parsed namespace from ID (post-init)
146
name: Parsed name from ID (post-init)
147
version: Parsed version from ID (post-init)
148
additional_wrappers: Tuple of additional wrapper specs
149
vector_entry_point: Entry point for vectorized environment
150
"""
151
152
class WrapperSpec:
153
"""
154
Wrapper specification for automatic wrapper application.
155
156
Attributes:
157
name: Wrapper name
158
entry_point: Import path to wrapper class
159
kwargs: Keyword arguments for wrapper constructor
160
"""
161
162
class VectorizeMode(Enum):
163
"""
164
Enumeration of vectorization modes.
165
166
Values:
167
SYNC: Synchronous vectorization
168
ASYNC: Asynchronous vectorization
169
VECTOR_ENTRY_POINT: Use custom vector entry point
170
"""
171
SYNC = "sync"
172
ASYNC = "async"
173
VECTOR_ENTRY_POINT = "vector_entry_point"
174
```
175
176
## Usage Examples
177
178
### Creating Environments from Registry
179
180
```python
181
import gymnasium as gym
182
183
# Create a standard environment
184
env = gym.make('CartPole-v1')
185
186
# Create with custom parameters
187
env = gym.make('CartPole-v1', render_mode='human')
188
189
# Create vectorized environments
190
vec_env = gym.make_vec('CartPole-v1', num_envs=4)
191
192
# Get environment specification
193
spec = gym.spec('CartPole-v1')
194
print(f"Max episode steps: {spec.max_episode_steps}")
195
print(f"Reward threshold: {spec.reward_threshold}")
196
```
197
198
### Registering Custom Environments
199
200
```python
201
from gymnasium.envs.registration import register
202
203
# Register a simple custom environment
204
register(
205
id='MyCustomEnv-v0',
206
entry_point='mypackage.envs:MyCustomEnv',
207
max_episode_steps=1000,
208
reward_threshold=500.0
209
)
210
211
# Register with additional wrappers
212
register(
213
id='MyWrappedEnv-v0',
214
entry_point='mypackage.envs:MyEnv',
215
additional_wrappers=[
216
{'name': 'TimeLimit', 'kwargs': {'max_episode_steps': 200}},
217
{'name': 'FlattenObservation', 'kwargs': {}}
218
]
219
)
220
221
# Now you can create instances
222
env = gym.make('MyCustomEnv-v0')
223
wrapped_env = gym.make('MyWrappedEnv-v0')
224
```
225
226
### Registry Exploration
227
228
```python
229
import gymnasium as gym
230
231
# Print all registered environments
232
gym.pprint_registry()
233
234
# Get specific environment spec
235
cartpole_spec = gym.spec('CartPole-v1')
236
print(f"Entry point: {cartpole_spec.entry_point}")
237
print(f"Max steps: {cartpole_spec.max_episode_steps}")
238
239
# Check if environment is registered
240
try:
241
spec = gym.spec('NonExistentEnv-v0')
242
except gym.error.UnregisteredEnv:
243
print("Environment not found")
244
```
245
246
### Namespace Management
247
248
```python
249
# Environments can be organized in namespaces
250
# Example: 'ALE/Breakout-v5' is in the 'ALE' namespace
251
252
# Create namespaced environment
253
atari_env = gym.make('ALE/Breakout-v5')
254
255
# Register in custom namespace
256
register(
257
id='MyNamespace/CustomEnv-v0',
258
entry_point='mypackage:MyEnv'
259
)
260
261
custom_env = gym.make('MyNamespace/CustomEnv-v0')
262
```
263
264
### Entry Point Registration
265
266
```python
267
# For packaging environments in separate packages
268
# In setup.py or pyproject.toml:
269
270
setup(
271
name='my-gym-envs',
272
entry_points={
273
'gymnasium.envs': [
274
'my_namespace:my_gym_envs.registration:register_envs'
275
]
276
}
277
)
278
279
# In my_gym_envs/registration.py:
280
def register_envs():
281
register(
282
id='MyNamespace/Env1-v0',
283
entry_point='my_gym_envs.envs:Env1'
284
)
285
register(
286
id='MyNamespace/Env2-v0',
287
entry_point='my_gym_envs.envs:Env2'
288
)
289
290
# Environments are auto-registered when package is installed
291
```