Skip to content

Commit dbe3366

Browse files
authored
add new function struct2dict (#139)
* add new function struct2dict * fix version to 1.10 * change struct2ntuple to use fieldnames
1 parent 54234b4 commit dbe3366

File tree

5 files changed

+22
-2
lines changed

5 files changed

+22
-2
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
# 1.10.0
2+
* New function `struct2ntuple` that converts a struct to a NamedTuple (for saving)
3+
14
# 1.9.0
25
* `savename` now has the `ignore` option.
36

Project.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
name = "DrWatson"
22
uuid = "634d3b9d-ee7a-5ddf-bec9-22491ea816e1"
33
repo = "https://github.com/JuliaDynamics/DrWatson.jl.git"
4-
version = "1.9.2"
4+
version = "1.10.0"
55

66
[deps]
77
FileIO = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"

docs/src/save.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,5 @@ See [Stopping "Did I run this?"](@ref) for an example usage of `produce_or_load`
6363
[`savename`](@ref) gives great support for getting a name out of any Julia composite type. To save something though, one needs a dictionary. So the following function can be conveniently used to directly save a struct using any saving function:
6464
```@docs
6565
struct2dict
66+
struct2ntuple
6667
```

src/saving_tools.jl

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -301,4 +301,14 @@ tagsave(savename(s), struct2dict(s))
301301
"""
302302
function struct2dict(s)
303303
Dict(x => getfield(s, x) for x in fieldnames(typeof(s)))
304-
end
304+
end
305+
306+
export struct2ntuple
307+
308+
"""
309+
struct2ntuple(s) -> n
310+
Convert a Julia composite type `s` to a NamedTuple `n`.
311+
"""
312+
function struct2ntuple(s)
313+
NamedTuple{fieldnames(typeof(s))}(( getfield(s, x) for x in fieldnames(typeof(s))))
314+
end

test/customize_savename.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,12 @@ for x in fieldnames(typeof(e1))
4646
@test d[x] == getfield(e1, x)
4747
end
4848

49+
nt = struct2ntuple(e1)
50+
@test isa(nt, NamedTuple)
51+
for x in fieldnames(typeof(e1))
52+
@test nt[x] == getfield(e1, x)
53+
end
54+
4955
# Test extra dir and default_prefix:
5056
s = savename(joinpath("path", "to", "data"), e1)
5157
@test s[1:4] == "path"

0 commit comments

Comments
 (0)