implement_for¶
- class torchrl._utils.implement_for(module_name: Union[str, Callable], from_version: Optional[str] = None, to_version: Optional[str] = None, *, class_method: bool = False)[source]¶
一個版本裝飾器,用於檢查環境中的版本並使用相符的版本實作函式。
如果指定的模組遺失或沒有合適的實作,呼叫裝飾的函式將導致明確的錯誤。 在範圍相交的情況下,將使用最後一個合適的實作。
此包裝器也可用於為同一個函式實作不同的後端 (例如,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
。
範例
>>> @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: Optional[Dict[str, implement_for]] = None)[原始碼]¶
重設 setter_dict 中的 setters。
setter_dict
是 implementations 的副本。 我們只需要遍歷其值並對每個值呼叫module_set()
即可。