Nix Language Quirks: Difference between revisions

Indented strings trim leading whitespace: Remove unnecessary sentence and clarify wording
Tags: Mobile edit Mobile web edit
Imports and namespaces: Reword and link to relevant with/import links. Also removed the last part about let binding inherit priority and different "types" of inherit, because it was completely wrong/misleading afaik
Line 75: Line 75:


== Imports and namespaces ==
== 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:
Nix includes a keyword <code>import</code>, but it's equivalent in other languages is <code>eval</code>.  
 
It is typically be used for namespacing:


  <syntaxHighlight lang=nix>let
  <syntaxHighlight lang=nix>let
Line 83: Line 85:
   pkgs.runCommand (lib.strings.removePrefix ".... </syntaxHighlight>
   pkgs.runCommand (lib.strings.removePrefix ".... </syntaxHighlight>


consider using <code>import</code> here as using <code>qualified import ...</code> in Haskell or <code>import ...</code> in Python.  
consider the use of <code>import</code> here similar to using <code>qualified import ...</code> in Haskell or <code>import ...</code> in Python. Another (discouraged and increasingly uncommon) way of importing is [https://nix.dev/manual/nix/2.24/language/syntax#with-expressions <code>with import ...;</code>], which corresponds to Python <code>from ... import *</code>. This use of <code>with</code> imports everything from the target into scope, which has numerous potential gotchas and problems, and so instead using [https://nix.dev/guides/best-practices#with-scopes <code>inherit</code>] is encouraged and preferred.
 
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:
 
  <syntaxHighlight lang=nix>
let
  lib = import <nixpkgs/lib>;
  inherit (lib.strings)
    removePrefix removeSuffix
  ;
  inherit (lib.lists)
    isList init drop
  ;
in
  removePrefix ... </syntaxHighlight>
 
<code>inherit</code> has higher priority than <code>with</code>, and conflicts with <code>let</code>
 
  <syntaxHighlight lang=nix>
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 </syntaxHighlight>
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.


== builtins.replaceStrings key match on "" ==
== builtins.replaceStrings key match on "" ==