TensorDictBase.setdefault#
- TensorDictBase.setdefault(key: NestedKey, default: Tensor | TensorCollection | Any, inplace: bool = False) Tensor | TensorCollection#
Returns the entry at
key, after writingdefaultthere if the key is missing.As for
dict.setdefault(), an existing entry is not changed. The result is read withget(), so a non-tensor entry returns itsNonTensorData.- Parameters:
key (NestedKey) – the key of the entry.
default (Tensor, TensorDictBase or any object) – the value written if the key is missing.
inplace (bool, optional) – passed to
set()whendefaultis written. Defaults toFalse.
- Raises:
RuntimeError – if the key is missing and the tensordict is locked, or if the leading dimensions of
defaultdo not match the batch size.
Examples
>>> import torch >>> from tensordict import TensorDict >>> td = TensorDict({}, batch_size=[3]) >>> td.setdefault("a", torch.zeros(3)) tensor([0., 0., 0.]) >>> td.setdefault("a", torch.ones(3)) # "a" exists: not changed tensor([0., 0., 0.])
Every tensordict class and every tensorclass has this method. For the other methods, see Methods by task.