-
Notifications
You must be signed in to change notification settings - Fork 7
Open
Description
The Graph.fromdict method lets us accept data from several formats in addition to the current YAML.
I have had some motivation recently to explore TOML input for demes, and code like this below "just works":
# requires python >= 3.11 (part of std lib)
# tomllib does not WRITE to toml.
import tomllib
# to read/write toml
import toml
# A toml writer mentioned in tomllib docs
import tomli_w
import demes
with open("example.toml") as f:
input = f.readlines()
input = "".join(input)
print(input, type(input))
parsed_with_toml = toml.loads(input)
parsed_with_tomllib = tomllib.loads(input)
print(f"parsed with toml = {parsed_with_toml}")
print(f"parsed with tomllib = {parsed_with_tomllib}")
graph_from_toml = demes.Graph.fromdict(parsed_with_toml)
graph_from_tomllib = demes.Graph.fromdict(parsed_with_tomllib)
print(f"demes.Graph from toml: \n{graph_from_toml}")
print(f"demes.Graph from tomllib: \n{graph_from_tomllib}")
assert graph_from_toml.isclose(graph_from_tomllib)
# NOTE: tomllib does NOT support WRITING toml...
graph_as_toml = toml.dumps(graph_from_toml.asdict())
print(f"graph back into toml = \n{graph_as_toml}")
# ... but tomli_w does
graph_as_toml_2 = tomli_w.dumps(graph_from_toml.asdict())
print(f"graph_from_toml via tomli_w = \n{graph_as_toml_2}")The contents of the example are:
time_units = "years"
description = "a description"
generation_time = 25
[defaults]
[defaults.migration]
rate = 0.25
demes = ["A", "B"]
[[demes]]
name = "A"
[[demes.epochs]]
start_size = 100
[[demes]]
name = "B"
[[demes.epochs]]
start_size = 42I also suspect that we get JSON support for free in a similar way.
We could add functions like demes.loads_toml (or toml_loads??), etc., which would be very thin wrappers around code like the above.
Or we can document somewhere that the asdict method is more useful than we've let on.
Thoughts?
Metadata
Metadata
Assignees
Labels
No labels