Nix syntax to conditionally add attributes into a set

Hi folks,

I have a few conditions that I want to use to create an attr. set. I could use the conditions to add attr. with a value or null:

{
  a = if x then 1 else null;
  b = if y then 2 else null;
}

But since this is supposed to be NixOS configuration it makes more sense to have just:

{
  a = 1;
  b = 2;
}
# or
{
  a = 1;
}
# or
{}

Since missing attr means: keep default / do not change.

Could you please tell me the proper way to do that in Nix lang?

I figured out this solution:

{ }
// (if x
then { a = 1; }
else { })
// (if y
then { b = 2; }
else { });

But it feels weird ;-).

Btw. I could ask the same question for a list and have code with ++ [] instead of // {}.

Is there a single place that collects all idioms commonly used in Nix? The lang is small and that means there must be a lot of idioms and I don’t want to reinvent wheel / I want to write nixonic (like pythonic) code ;-).

Thank you.

You might be interested by lib.attrsets.optionalAttrs x y that is like if x then y else {}. You also have similar functions for lists, just search optional in Nix (builtins) & Nixpkgs (lib) Functions See Conditionally set attribute - #10 by NobbZ for a similar discution

Thank you. The second link was super helpful ;-).

After looking at lib.*optional* my stupid if x then y else {} looks better (from my personal readability perspective).