Convert Figma logo to code with AI

crdoconnor logostrictyaml

Type-safe YAML parser and validator.

1,458
61
1,458
93

Top Related Projects

2,524

Canonical source repository for PyYAML

A YAML parser and emitter in C++

6,265

JavaScript YAML parser and dumper. Very fast.

Quick Overview

The crdoconnor/strictyaml project is a YAML parsing library for Python that enforces strict type checking and validation. It aims to provide a more robust and reliable way of working with YAML data in Python applications.

Pros

  • Strict Type Checking: The library enforces strict type checking, ensuring that the YAML data conforms to the expected data types, which helps catch errors early in the development process.
  • Validation: The library provides a rich set of validation rules that can be applied to the YAML data, helping to ensure the data's integrity and consistency.
  • Readable Error Messages: When validation fails, the library provides detailed and informative error messages, making it easier to diagnose and fix issues.
  • Extensibility: The library is designed to be extensible, allowing developers to define custom data types and validation rules to suit their specific needs.

Cons

  • Performance: The strict type checking and validation features of the library may result in slightly slower parsing performance compared to other YAML parsing libraries.
  • Learning Curve: The library's advanced features and validation rules may have a steeper learning curve for developers who are new to the project.
  • Limited Ecosystem: As a specialized YAML parsing library, strictyaml may have a smaller ecosystem of third-party libraries and tools compared to more widely used YAML parsing libraries.
  • Dependency on PyYAML: The library is built on top of the PyYAML library, which means that it inherits any limitations or issues that may exist in PyYAML.

Code Examples

Here are a few examples of how to use the strictyaml library:

from strictyaml import load, Map, Str, Int

# Define a YAML schema
schema = Map({
    "name": Str(),
    "age": Int()
})

# Load YAML data and validate it against the schema
data = load("""
    name: John Doe
    age: 30
""", schema)

print(data["name"])  # Output: "John Doe"
print(data["age"])   # Output: 30

In this example, we define a YAML schema using the Map and Str/Int data types provided by the strictyaml library. We then load and validate the YAML data against the schema, and access the individual data fields.

from strictyaml import load, Map, Seq, Str, Int

# Define a YAML schema for a list of users
schema = Map({
    "users": Seq(Map({
        "name": Str(),
        "age": Int()
    }))
})

# Load YAML data and validate it against the schema
data = load("""
    users:
        - name: John Doe
          age: 30
        - name: Jane Smith
          age: 25
""", schema)

for user in data["users"]:
    print(f"{user['name']} ({user['age']})")

In this example, we define a more complex YAML schema that includes a list of user objects, each with a name and age field. We then load and validate the YAML data against the schema, and iterate over the list of users to print their names and ages.

Getting Started

To get started with the strictyaml library, you can install it using pip:

pip install strictyaml

Once installed, you can start using the library in your Python code. Here's a simple example of how to load and validate YAML data:

from strictyaml import load, Map, Str, Int

# Define a YAML schema
schema = Map({
    "name": Str(),
    "age": Int()
})

# Load YAML data and validate it against the schema
data = load("""
    name: John Doe
    age: 30
""", schema)

print(data["name"])  # Output: "John Doe"
print(data["age"])   # Output: 30

In this example, we first define a YAML schema using the Map and Str/Int data types provided by the strictyaml library. We then load and validate the YAML data against the schema, and access the individual data fields.

For

Competitor Comparisons

2,524

Canonical source repository for PyYAML

Pros of PyYAML

  • More feature-rich, supporting all YAML 1.1 specifications
  • Widely adopted and well-established in the Python ecosystem
  • Offers both safe and unsafe loading options for flexibility

Cons of PyYAML

  • Can be less secure due to potential arbitrary code execution risks
  • More complex API and usage, requiring careful handling
  • Allows implicit typing, which can lead to unexpected behavior

Code Comparison

PyYAML:

import yaml

data = yaml.safe_load("""
key: value
list:
  - item1
  - item2
""")

StrictYAML:

from strictyaml import load

data = load("""
key: value
list:
  - item1
  - item2
""")

Key Differences

StrictYAML focuses on simplicity and safety, offering a more restricted but secure YAML parsing experience. It enforces explicit schemas and disallows implicit typing, reducing potential security risks and unexpected behavior.

PyYAML provides a more comprehensive YAML implementation, supporting advanced features and offering more flexibility. However, this comes at the cost of increased complexity and potential security concerns if not used carefully.

StrictYAML is designed for straightforward data serialization tasks, while PyYAML is better suited for complex YAML processing needs where full YAML 1.1 support is required.

A YAML parser and emitter in C++

Pros of yaml-cpp

  • Written in C++, offering high performance and low-level system integration
  • Supports both YAML 1.1 and 1.2 specifications
  • Provides a more comprehensive feature set for complex YAML structures

Cons of yaml-cpp

  • Less focus on strict parsing and validation compared to StrictYAML
  • More complex API, potentially leading to a steeper learning curve
  • Lacks built-in schema validation features

Code Comparison

yaml-cpp:

#include <yaml-cpp/yaml.h>

YAML::Node config = YAML::LoadFile("config.yaml");
std::string value = config["key"].as<std::string>();

StrictYAML:

from strictyaml import load, Map, Str

schema = Map({"key": Str()})
data = load(open("config.yaml").read(), schema)
value = data["key"]

Key Differences

  • Language: yaml-cpp is C++, while StrictYAML is Python
  • Parsing approach: yaml-cpp offers more flexibility, StrictYAML enforces stricter parsing rules
  • Validation: StrictYAML includes built-in schema validation, yaml-cpp requires manual validation
  • Use cases: yaml-cpp is suitable for performance-critical applications, StrictYAML focuses on data validation and safety

Both libraries have their strengths, with yaml-cpp offering more flexibility and performance, while StrictYAML prioritizes data integrity and ease of use for Python developers.

6,265

JavaScript YAML parser and dumper. Very fast.

Pros of js-yaml

  • Widely adopted and well-established in the JavaScript ecosystem
  • Supports both YAML 1.1 and 1.2 specifications
  • Offers extensive customization options and advanced features

Cons of js-yaml

  • Less focus on strict parsing and validation
  • May allow potentially unsafe YAML constructs by default
  • Larger library size due to comprehensive feature set

Code Comparison

js-yaml:

const yaml = require('js-yaml');
const obj = yaml.load('foo: bar\nbaz: 42');
console.log(obj);

strictyaml:

from strictyaml import load
schema = Map({"foo": Str(), "baz": Int()})
data = load("foo: bar\nbaz: 42", schema)
print(data.data)

Key Differences

  • strictyaml prioritizes safety and strict parsing, while js-yaml offers more flexibility
  • js-yaml is JavaScript-based, whereas strictyaml is Python-based
  • strictyaml requires explicit schema definitions, js-yaml can parse without predefined schemas
  • js-yaml supports more YAML features, while strictyaml intentionally limits supported constructs

Use Cases

  • js-yaml: General-purpose YAML parsing in JavaScript projects, especially when flexibility is needed
  • strictyaml: Python projects requiring strict YAML validation and safer parsing

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

StrictYAML

StrictYAML is a type-safe YAML parser that parses and validates a restricted subset of the YAML specification.

Priorities:

  • Beautiful API
  • Refusing to parse the ugly, hard to read and insecure features of YAML like the Norway problem.
  • Strict validation of markup and straightforward type casting.
  • Clear, readable exceptions with code snippets and line numbers.
  • Acting as a near-drop in replacement for pyyaml, ruamel.yaml or poyo.
  • Ability to read in YAML, make changes and write it out again with comments preserved.
  • Not speed, currently.

Simple example:

# All about the character
name: Ford Prefect
age: 42
possessions:
- Towel

from strictyaml import load, Map, Str, Int, Seq, YAMLError

Default parse result:

>>> load(yaml_snippet)
YAML({'name': 'Ford Prefect', 'age': '42', 'possessions': ['Towel']})

All data is string, list or OrderedDict:

>>> load(yaml_snippet).data
{'name': 'Ford Prefect', 'age': '42', 'possessions': ['Towel']}

Quickstart with schema:

from strictyaml import load, Map, Str, Int, Seq, YAMLError

schema = Map({"name": Str(), "age": Int(), "possessions": Seq(Str())})

42 is now parsed as an integer:

>>> person = load(yaml_snippet, schema)
>>> person.data
{'name': 'Ford Prefect', 'age': 42, 'possessions': ['Towel']}

A YAMLError will be raised if there are syntactic problems, violations of your schema or use of disallowed YAML features:

# All about the character
name: Ford Prefect
age: 42

For example, a schema violation:

try:
    person = load(yaml_snippet, schema)
except YAMLError as error:
    print(error)

while parsing a mapping
  in "<unicode string>", line 1, column 1:
    # All about the character
     ^ (line: 1)
required key(s) 'possessions' not found
  in "<unicode string>", line 3, column 1:
    age: '42'
    ^ (line: 3)

If parsed correctly:

from strictyaml import load, Map, Str, Int, Seq, YAMLError, as_document

schema = Map({"name": Str(), "age": Int(), "possessions": Seq(Str())})

You can modify values and write out the YAML with comments preserved:

person = load(yaml_snippet, schema)
person['age'] = 43
print(person.as_yaml())

# All about the character
name: Ford Prefect
age: 43
possessions:
- Towel

As well as look up line numbers:

>>> person = load(yaml_snippet, schema)
>>> person['possessions'][0].start_line
5

And construct YAML documents from dicts or lists:

print(as_document({"x": 1}).as_yaml())

x: 1

Install

$ pip install strictyaml

Why StrictYAML?

There are a number of formats and approaches that can achieve more or less the same purpose as StrictYAML. I've tried to make it the best one. Below is a series of documented justifications:

Using StrictYAML

How to:

Compound validators:

Scalar validators:

Restrictions:

Design justifications

There are some design decisions in StrictYAML which are controversial and/or not obvious. Those are documented here:

Star Contributors

  • @wwoods
  • @chrisburr
  • @jnichols0

Other Contributors

  • @eulores
  • @WaltWoods
  • @ChristopherGS
  • @gvx
  • @AlexandreDecan
  • @lots0logs
  • @tobbez
  • @jaredsampson
  • @BoboTIG

StrictYAML also includes code from ruamel.yaml, Copyright Anthon van der Neut.

Contributing

  • Before writing any code, please read the tutorial on contributing to hitchdev libraries.
  • Before writing any code, if you're proposing a new feature, please raise it on github. If it's an existing feature / bug, please comment and briefly describe how you're going to implement it.
  • All code needs to come accompanied with a story that exercises it or a modification to an existing story. This is used both to test the code and build the documentation.