Skip to content

Commit

Permalink
Automatically convert String keys to Symbols in access. (#282)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
ulido authored Sep 2, 2021
1 parent 95db790 commit 22314c4
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/naming.jl
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,10 @@ For example, if `c, c.k1` are `NamedTuple`s then
access(c, keys...) = access(access(c, keys[1]), Base.tail(keys)...)
access(c::AbstractDict, key) = getindex(c, key)
access(c, key) = getproperty(c, key)
# Automatically convert String keys to Symbols (for structs)...
access(c, key::AbstractString) = access(c, Symbol(key))
# ...but we need to explicitly allow for String keys in Dicts.
access(c::AbstractDict, key::AbstractString) = getindex(c, key)

"""
allignore(c) = ()
Expand Down
6 changes: 6 additions & 0 deletions test/naming_tests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,12 @@ x = A(5, (b = 3, c = 4))

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

# automatic string to symbol conversion in accesses of structs
@test savename(x, accesses=("a",)) == "a=5"
# But test that this conversion does not happen for Dicts!
mixed_str_sym_dict = Dict("a" => 1, :b => 2)
@test savename(mixed_str_sym_dict, accesses=("a", :b)) == "a=1_b=2"

# empty container
x = A(5, NamedTuple())
@test !occursin("p", savename(x))
Expand Down

0 comments on commit 22314c4

Please sign in to comment.