implement_for¶
- class torchrl.implement_for(module_name: str | Callable[[], Any], from_version: str | None = None, to_version: str | None = None, *, class_method: bool = False, compilable: bool = False)[源代码]¶
一个版本装饰器,用于检查版本兼容性并实现函数。
如果指定的模块丢失或没有合适的实现,装饰函数的调用将导致显式错误。在范围交叉的情况下,将使用最后一次合适的实现。
此包装器还可用于为同一函数实现不同的后端(例如,gym vs gymnasium,numpy vs jax-numpy 等)。
- 参数:
module_name (str 或 callable) – 检查此名称模块的版本(例如,“gym”)。如果提供了 callable,它应返回模块。
from_version – 实现兼容的版本。可以是开放的(None)。
to_version – 实现不再兼容的版本。可以是开放的(None)。
- 关键字参数:
class_method (bool, optional) – 如果为
True
,则函数将被编写为类方法。默认为False
。compilable (bool, optional) – 如果为
False
,则模块导入仅在第一次调用被包装函数时发生。如果为True
,则在被包装函数初始化时导入模块。默认为False
。
示例
>>> @implement_for("gym", "0.13", "0.14") >>> def fun(self, x): ... # Older gym versions will return x + 1 ... return x + 1 ... >>> @implement_for("gym", "0.14", "0.23") >>> def fun(self, x): ... # More recent gym versions will return x + 2 ... return x + 2 ... >>> @implement_for(lambda: import_module("gym"), "0.23", None) >>> def fun(self, x): ... # More recent gym versions will return x + 2 ... return x + 2 ... >>> @implement_for("gymnasium", None, "1.0.0") >>> def fun(self, x): ... # If gymnasium is to be used instead of gym, x+3 will be returned ... return x + 3 ...
这表明该函数与 gym 0.13+ 兼容,但与 gym 0.14+ 不兼容。
- classmethod reset(setters_dict: dict[str, implement_for] | None = None) None [源代码]¶
重置 setter_dict 中的设置器。
- 参数:
setters_dict – 实现的副本。我们遍历其值并为每个值调用
module_set()
。