Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Warn when inheriting attributes from a function call #55

Open
ilkecan opened this issue Sep 24, 2022 · 1 comment
Open

Warn when inheriting attributes from a function call #55

ilkecan opened this issue Sep 24, 2022 · 1 comment
Assignees
Labels
enhancement New feature or request

Comments

@ilkecan
Copy link
Contributor

ilkecan commented Sep 24, 2022

It is possible to inherit attributes from another set1. For example:

let
  x = { a = 1; b = 2; }
  y = { inherit (x) a b; }
in
y # evaluates to `{ a = 1; b = 2; }`

But since Nix does not have maximal laziness, inheriting from the result of a function call will evaluate the function for each inherited attribute. That is, evaluating the expression below:

let
  f = x:
    builtins.trace "evaluated" {
      a = x + 1;
      b = x + 2;
    };
  inherit (f 0) a b;
in
[ a b ]

will evaluate f 0 2 times (which can be checked with trace). This can be avoided with:

let
  f = x:
    builtins.trace "evaluated" {
      a = x + 1;
      b = x + 2;
    };
  set = f 0;
  inherit (set) a b;
in
[ a b ]

In this case f 0 will be evaluated only once because the result is saved in a variable.


An exception to this is import. While the manual notes that import is a regular function, result of import <path> seems to be cached internally, so:

let
  inherit (import <path>) f g;            # this is OK
  inherit (import <path> <some-args>) f g # this is not OK 
in

Footnotes

  1. https://nixos.org/manual/nix/unstable/language/constructs.html#inheriting-attributes

@oppiliappan
Copy link
Owner

aha, this is a very nice lint idea, thanks!

@oppiliappan oppiliappan self-assigned this Jan 8, 2023
@oppiliappan oppiliappan added the enhancement New feature or request label Jan 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants