Skip to content

Commit 22314c4

Browse files
authored
Automatically convert String keys to Symbols in access. (#282)
To make the `savename` `accesses` keyword syntax easier, allow automatic conversion of `String` keys to `Symbol`s when working with containers other than `Dict`s. Explicitly continue to allow `String` keys for `Dict`s. Includes tests for `String` key to `Symbol` conversion when handling a struct, and `String` key pass through when handling a `Dict`. Closes #259.
1 parent 95db790 commit 22314c4

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

src/naming.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,10 @@ For example, if `c, c.k1` are `NamedTuple`s then
185185
access(c, keys...) = access(access(c, keys[1]), Base.tail(keys)...)
186186
access(c::AbstractDict, key) = getindex(c, key)
187187
access(c, key) = getproperty(c, key)
188+
# Automatically convert String keys to Symbols (for structs)...
189+
access(c, key::AbstractString) = access(c, Symbol(key))
190+
# ...but we need to explicitly allow for String keys in Dicts.
191+
access(c::AbstractDict, key::AbstractString) = getindex(c, key)
188192

189193
"""
190194
allignore(c) = ()

test/naming_tests.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,12 @@ x = A(5, (b = 3, c = 4))
8686

8787
@test savename(x) == "a=5_p=(b=3,c=4)"
8888

89+
# automatic string to symbol conversion in accesses of structs
90+
@test savename(x, accesses=("a",)) == "a=5"
91+
# But test that this conversion does not happen for Dicts!
92+
mixed_str_sym_dict = Dict("a" => 1, :b => 2)
93+
@test savename(mixed_str_sym_dict, accesses=("a", :b)) == "a=1_b=2"
94+
8995
# empty container
9096
x = A(5, NamedTuple())
9197
@test !occursin("p", savename(x))

0 commit comments

Comments
 (0)