Rate this Page
★ ★ ★ ★ ★

TensorDictBase.setdefault#

TensorDictBase.setdefault(key: NestedKey, default: Tensor | TensorCollection | Any, inplace: bool = False) → Tensor | TensorCollection#

Inserts the key entry with a value of default if key is not in the tensordict.

Returns the value for key if key is in the tensordict, else default.

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() when default is written. Defaults to False.

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.

Tutorials that use setdefault#

Getting, setting, and nesting keys

Getting, setting, and nesting keys