Skip to content

Commit

Permalink
Add support for including module with gym.make (#2815)
Browse files Browse the repository at this point in the history
  • Loading branch information
arjun-kg authored May 23, 2022
1 parent e226602 commit a37b956
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
11 changes: 10 additions & 1 deletion gym/envs/registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,7 @@ def make(
if they follow the gym API. To disable this feature, set parameter `disable_env_checker=True`.
Args:
id: Name of the environment.
id: Name of the environment. Optionally, a module to import can be included, eg. 'module:Env-v0'
max_episode_steps: Maximum length of an episode (TimeLimit wrapper).
autoreset: Whether to automatically reset the environment after each episode (AutoResetWrapper).
disable_env_checker: If to disable the environment checker
Expand All @@ -516,6 +516,15 @@ def make(
if isinstance(id, EnvSpec):
spec_ = id
else:
module, id = (None, id) if ":" not in id else id.split(":")
if module is not None:
try:
importlib.import_module(module)
except ModuleNotFoundError as e:
raise ModuleNotFoundError(
f"{e}. Environment registration via importing a module failed. "
f"Check whether '{module}' contains env registration and can be imported."
)
spec_ = registry.get(id)

ns, name, version = parse_env_id(id)
Expand Down
21 changes: 21 additions & 0 deletions tests/envs/register_during_make_env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import gym


class RegisterDuringMakeEnv(gym.Env):
"""Used in `test_registration.py` to check if `env.make` can import and register an env"""

def __init__(self):
self.action_space = gym.spaces.Discrete(1)
self.observation_space = gym.spaces.Discrete(1)

def reset(self, *, seed=None, return_info=True, options=None):
return 0, {}

def step(self, action):
return 0, 0, False, {}


gym.register(
"RegisterDuringMakeEnv-v0",
entry_point="tests.envs.register_during_make_env:RegisterDuringMakeEnv",
)
5 changes: 5 additions & 0 deletions tests/envs/test_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,3 +291,8 @@ def test_namespace():

del registry["MyDefaultNamespace/MyDefaultEnvironment-v0"]
del registry["MyDefaultEnvironment-v1"]


def test_import_module_during_make():
# Test custom environment which is registered at make
gym.make("tests.envs.register_during_make_env:RegisterDuringMakeEnv-v0")

0 comments on commit a37b956

Please sign in to comment.