TensorDictBase.setdefault#
- TensorDictBase.setdefault(key: NestedKey, default: Tensor | TensorCollection | Any, inplace: bool = False) Tensor | TensorCollection#
Inserts the
keyentry with a value ofdefaultifkeyis not in the tensordict.Returns the value for
keyifkeyis in the tensordict, elsedefault.- Parameters:
key (NestedKey) – the name of the value.
default (Tensor or compatible type, TensorDictBase) – value to be stored in the tensordict if the key is not already present.
inplace (bool, optional) – passed to
set()whendefaultis written. Defaults toFalse.
- Returns:
The value of key in the tensordict. Will be default if the key was not previously set.
Examples
>>> import torch >>> from tensordict import TensorDict >>> td = TensorDict({}, batch_size=[3, 4]) >>> val = td.setdefault("a", torch.zeros(3, 4)) >>> assert (val == 0).all() >>> val = td.setdefault("a", torch.ones(3, 4)) >>> assert (val == 0).all() # output is still 0
Every tensordict class and every tensorclass has this method. For the other methods, see Methods by task.