qml.pytrees.flatten

flatten(obj, is_leaf=None)[source]

Flattens a pytree into leaves and a structure.

Parameters
  • obj (Any) – any object.

  • is_leaf (Callable[[Any], bool] | None = None) – an optionally specified function that will be called at each flattening step. It should return a boolean, with True stopping the traversal and the whole subtree being treated as a leaf, and False indicating the flattening should traverse the current object.

Returns

a list of leaves and a structure representing the object

Return type

List[Any], Union[Structure, Leaf]

See also unflatten().

Example

>>> op = qml.adjoint(qml.Rot(1.2, 2.3, 3.4, wires=0))
>>> data, structure = flatten(op)
>>> data
[1.2, 2.3, 3.4]
>>> structure
<PyTree(AdjointOperation, (), (<PyTree(Rot, (Wires([0]), ()), (Leaf, Leaf, Leaf))>,))>