StrictYAML is a type-safe YAML parser that parses a restricted subset of the YAML specificaton.
Priorities:
- Readability of YAML.
- Ease of use of API.
- Secure by default.
- Strict validation of markup and straightforward type casting.
- Clear, human readable exceptions with line numbers.
- Acting as a near-drop in replacement for pyyaml, ruamel.yaml or poyo.
- Roundtripping - reading in (commented) YAML and writing it out with comments.
- Letting you worry about more interesting things than parsing or writing config files.
Simple example:
# All about the character
name: Ford Prefect
age: 42
possessions:
- Towel
Default parse result:
>>> strictyaml.load(yaml)
YAML({'possessions': ['Towel'], 'age': '42', 'name': 'Ford Prefect'})
>>> strictyaml.load(yaml).data
{"name": "Ford Prefect", "age": "42", "possessions": ["Towel", ]} # All data is str, list or dict
Using a schema:
>>> from strictyaml import load, Map, Str, Int, Seq
>>> person = load(yaml, Map({"name": Str(), "age": Int(), "possessions": Seq(Str())})) \
>>> person.data == {"name": "Ford Prefect", "age": 42, "possessions": ["Towel", ]} # 42 is now an int
Once parsed you can change values and roundtrip the whole YAML, with comments preserved:
>>> person['age'] = load('43')
>>> print(person.as_yaml())
# All about the character
name: Ford Prefect
age: 43
possessions:
- Towel
As well as look up line numbers:
>>> person['possessions'][0].start_line
5
See more example driven documentation.
$ pip install strictyaml
From learning programmers:
If you're looking at this and thinking "why not do/use X instead?" that's a healthy response, and you deserve answers. These are probably the questions you're asking:
- Why should I use strictyaml instead of ordinary YAML?
- What features does StrictYAML remove?
- Why not use JSON for configuration or DSLs?
- Why not use INI files for configuration or DSLs?
- Why shouldn't I just use python for configuration?
- Why not use XML for configuration or DSLs?
- Why not use TOML?
- Why not use HJSON?
- Why not use JSON5?
- Why not use HOCON?
- Why not use pykwalify to validate YAML instead?
- What if I still disagree with everything you wrote here?
0.5: Data is now parsed by default as a YAML object instead of directly to dict/list. To get dict/list and ordinary values as before, get yaml_object.data.
0.7: Roundtripping now requires that you only assign YAML objects to index: e.g. yaml_object['x'] = another_yaml_obj
- @gvx
- @AlexandreDecan
- @lots0logs