query
On this page

attrByPath

lib.attrsets.attrByPath

Docs pulled from | This Revision | 10 minutes ago


Return an attribute from nested attribute sets.

Nix has an attribute selection operator . or which is sufficient for such queries, as long as the number of attributes is static. For example:

(x.a.b or 6) == attrByPath ["a" "b"] 6 x
# and
(x.${f p}."example.com" or 6) == attrByPath [ (f p) "example.com" ] 6 x

Inputs

attrPath

A list of strings representing the attribute path to return from set

default

Default value if attrPath does not resolve to an existing value

set

The nested attribute set to select values from

Type

attrByPath :: [String] -> Any -> AttrSet -> Any

Examples

lib.attrsets.attrByPath usage example

x = { a = { b = 3; }; }
# ["a" "b"] is equivalent to x.a.b
# 6 is a default value to return if the path does not exist in attrset
attrByPath ["a" "b"] 6 x
=> 3
attrByPath ["z" "z"] 6 x
=> 6

Noogle detected

Aliases

Implementation

The following is the current implementation of this function.

attrByPath =
    attrPath:
    default:
    set:
    let
      lenAttrPath = length attrPath;
      attrByPath' = n: s: (
        if n == lenAttrPath then s
        else (
          let
            attr = elemAt attrPath n;
          in
          if s ? ${attr} then attrByPath' (n + 1) s.${attr}
          else default
        )
      );
    in
      attrByPath' 0 set;