Proposal: add get_env/2, fetch_env/1 and fetch_env!/1

50 views
Skip to first unread message

thia.md...@gmail.com

unread,
Dec 18, 2018, 11:09:12 AM12/18/18
to elixir-lang-core
Hi,

Would be great if we had in the System module functions similar to those that we have right now in the Application module.

`System.get_env/2` could accept a default value similar to `Application.get_env/3`. I always find myself using System.get_env("VAR") || "DEFAULT VALUE".

And we could have `System.fetch_env/1` and `System.fetch_env!/1`. The fetch_env!/1 I would use a lot. Normally you want to raise an error if the variable does not exists and would be great if the already existed an function to do that. Right we have to use Map.fetch! `Map.fetch!(System.get_env(), "VAR")` or create our own custom function that raises an error. I think that as it is a common use case would make sense to include this functions in the language.

What do you guys think?

Thanks,
Thiago

Eric Camalionte

unread,
Dec 18, 2018, 11:21:22 AM12/18/18
to elixir-lang-core
Great idea Thiago! I would love this option. Especially to avoid this kind of implementation during the app initialization:

fetch! = fn key ->
  case System.get_env(key) do
    nil -> raise ArgumentError, "Could not fetch environment #{key} because configuration #{key} was not set"
    value -> value
  end
end 

fetch!.("SOME_ENV_HERE")



Hylke Alons

unread,
Dec 18, 2018, 12:03:49 PM12/18/18
to elixir-lang-core
It has been proposed various times.

thia.md...@gmail.com

unread,
Jan 4, 2019, 5:59:48 AM1/4/19
to elixir-lang-core
Hylke Alons good point, thanks! But this only applies to my proposal for System.get_env/3.

But I think we still need some discussion around System.fetch_env/1 and System.fetch_env!. I assume that the use cases for these functions are quite common, we usually want to raise an error in case a environment variable is missing.

What do you think?

Thanks,
Thiago
Reply all
Reply to author
Forward
0 new messages