Nix Language Quirks: Difference between revisions

imported>Danbst
added function argument destructuring
imported>Danbst
added imports and namespacing section
Line 55: Line 55:


These <code>x</code> and <code>y</code> are in fact <code>let</code>-bindings, but overridable ones.
These <code>x</code> and <code>y</code> are in fact <code>let</code>-bindings, but overridable ones.
== Imports and namespaces ==
There is a keyword <code>import</code>, but it's equivalent in other languages is  <code>eval</code>. It can be used for namespacing too:
<nowiki>let
  pkgs = import <nixpkgs> {};
  lib = import <nixpkgs/lib>;
in
  pkgs.runCommand (lib.strings.removePrefix "....</nowiki>
consider using <code>import</code> here as using <code>qualified import ...</code> in Haskell or <code>import ...</code> in Python.
Another way of importing is <code>with import ...;</code>, which corresponds to Python <code>from ... import *</code>.
But because of not very great IDE support in Nix, <code>with import ...;</code> is discouraged. Rather use <code>inherit</code>, especially if you are targeting source code for Nix newcomers:
<nowiki>
let
  lib = import <nixpkgs/lib>;
  inherit (lib.strings)
    removePrefix removeSuffix
  ;
  inherit (lib.lists)
    isList init drop
  ;
in
  removePrefix ...</nowiki>
<code>inherit</code> has higher priority than <code>with</code>, and conflicts with <code>let</code>
<nowiki>
nix-repl> let pkgs = { x = 1; }; x = 2; x = 3; inherit (pkgs) x; in x
error: attribute ‘x’ at (string):1:31 already defined at (string):1:24</nowiki>
This makes it a sane citizen of Nix lanugage... except it has a twin, called <code>{ inherit ...; }</code>. They DON'T do the same - <code>let inherit ...</code> adds let-bindings, and <code>{ inherit ...; }</code> adds attributes to a record.