Skip to content

Commit 21e649a

Browse files
author
José Valim
committed
Add deprecation and warning of Access.key/1 behaviour, closes #5548
1 parent c599956 commit 21e649a

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,7 @@ It is also possible to install escripts and archives by providing a Git/GitHub r
179179

180180
#### Elixir
181181

182+
* [Access] Do not accept nils in `Access.key/1` and `Access.key/2` in favor of explicit default values
182183
* [Float] Avoid multiple roundings in `Float.ceil/2`, `Float.floor/2` and `Float.round/2`
183184
* [Kernel] Don't crash in `macro_exported?/3` when dealing with Erlang modules
184185
* [Kernel] Ensure locals calls are rewritten when calling a local function or macro from inside a module
@@ -222,6 +223,7 @@ It is also possible to install escripts and archives by providing a Git/GitHub r
222223

223224
#### Elixir
224225

226+
* [Access] `Access.key/1` is deprecated due to erratic behaviour for missing keys, please use Access.key/2 instead with proper default values
225227
* [Behaviour] The `Behaviour` module is deprecated. Callbacks may now be defined directly via the `@callback` attribute
226228
* [Enum] Deprecate `Enum.uniq/2` in favor of `Enum.uniq_by/2`
227229
* [Float] `Float.to_char_list/2` and `Float.to_string/2` are deprecated (use the :erlang functions if such conversions are desired)

lib/elixir/lib/access.ex

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,27 @@ defmodule Access do
358358

359359
## Accessors
360360

361+
@doc false
362+
def key(key) do
363+
IO.warn "Access.key/1 is deprecated due to erratic behaviour for missing keys, " <>
364+
"please use Access.key/2 instead with proper default values"
365+
366+
fn
367+
:get, data, next ->
368+
next.(Map.get(to_map(data), key))
369+
:get_and_update, data, next ->
370+
value = Map.get(to_map(data), key)
371+
case next.(value) do
372+
{get, update} -> {get, Map.put(data, key, update)}
373+
:pop -> {value, Map.delete(data, key)}
374+
end
375+
end
376+
end
377+
378+
defp to_map(nil), do: %{}
379+
defp to_map(%{} = map), do: map
380+
defp to_map(data), do: raise "Access.key/1 expected a map/struct or nil, got: #{inspect data}"
381+
361382
@doc """
362383
Returns a function that accesses the given key in a map/struct.
363384
@@ -397,7 +418,7 @@ defmodule Access do
397418
** (BadMapError) expected a map, got: []
398419
399420
"""
400-
def key(key, default \\ nil) do
421+
def key(key, default) do
401422
fn
402423
:get, data, next ->
403424
next.(Map.get(data, key, default))

0 commit comments

Comments
 (0)