Practical use for the `only` function?

I’ve tried to search around github a bit, but only is a pretty common word. Can someone give me an example of a practical use for this function?

AbstractDifferentiation uses only because derivative/grad/jacobian functions are forced to return tuples with respect to each input, but these tuples must be length one in some cases. Users might mess these cases up when they define custom derivative rules, so this can help catch them.

3 Likes

Yes, to expand on what @jacobusmmsmit said, only is useful when a function generally returns a collection of elements, but you know that the collection should contain just a single element in your specific case and would be invalid otherwise. only helps you catch the invalid states.

EDIT: You could view only as a shortcut, I guess:

elements = some_function()
@assert length(elements) == 1
x = elements[begin]

# or with `only`

elements = some_function()
x = only(elements)
4 Likes