### Install StrictYAML Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/src/index.md This command installs the StrictYAML library using pip, the Python package installer. It's the standard way to get StrictYAML set up in your development environment. ```sh $ pip install strictyaml ``` -------------------------------- ### Installing StrictYAML Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/index.md Provides the command-line instruction to install the `strictyaml` Python package using `pip`, the standard package installer for Python. ```sh $ pip install strictyaml ``` -------------------------------- ### Example TOML Document Structure Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/src/why-not/toml.md Illustrates the basic structure of a TOML configuration file, including key-value pairs, tables, and date types. This example serves to show the syntax of TOML documents, which are discussed as being verbose. ```toml # This is a TOML document. title = "TOML Example" [owner] name = "Tom Preston-Werner" dob = 1979-05-27T07:32:00-08:00 # First class dates ``` -------------------------------- ### JSON5 Syntax Example Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/src/why-not/json5.md An example of JSON5 syntax, demonstrating unquoted keys, single-quoted string values, and a boolean literal, showcasing its hybrid nature between JSON and YAML. ```json { foo: 'bar', while: true, } ``` -------------------------------- ### Install StrictYAML Python package Source: https://github.com/crdoconnor/strictyaml/blob/master/README.md Command to install the StrictYAML library using Python's package installer, pip. This is the standard and recommended way to get StrictYAML set up in a Python environment. ```sh $ pip install strictyaml ``` -------------------------------- ### JSON5 Example Syntax Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/why-not/json5.md An example of JSON5 syntax, demonstrating its hybrid nature between YAML and JSON, including unquoted keys and trailing commas, which are features not present in standard JSON. ```json { foo: 'bar', while: true, } ``` -------------------------------- ### Get start line of YAML keys Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/what-line.md Shows how to retrieve the starting line number of a YAML key itself using `strictyaml`'s `keys()` method and the `.start_line` property on the key object. ```python Ensure(snippet.keys()[1].start_line).equals(3) ``` -------------------------------- ### Simple StrictYAML Document Example Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/why-not/toml.md Presents a basic StrictYAML document, showcasing its clean syntax for representing a map with string keys and values, an integer, and a list of strings. This example highlights StrictYAML's readability and minimal syntactic cruft. ```yaml # All about the character name: Ford Prefect age: 42 possessions: - Towel ``` -------------------------------- ### SDLang Syntax Examples Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/why-not/sdlang.md Illustrates various SDLang syntax features including single and multiple values, attributes, nested nodes, anonymous nodes, and matrix definitions. ```SDLang // This is a node with a single string value title "Hello, World" // Multiple values are supported, too bookmarks 12 15 188 1234 // Nodes can have attributes author "Peter Parker" email="peter@example.org" active=true // Nodes can be arbitrarily nested contents { section "First section" { paragraph "This is the first paragraph" paragraph "This is the second paragraph" } } // Anonymous nodes are supported "This text is the value of an anonymous node!" // This makes things like matrix definitions very convenient matrix { 1 0 0 0 1 0 0 0 1 } ``` -------------------------------- ### Basic TOML Document Example Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/why-not/toml.md Illustrates a simple TOML document structure, including a top-level key-value pair and a nested table with a string, an integer, and a date-time value. This example demonstrates TOML's syntax for defining sections and various data types. ```toml # This is a TOML document. title = "TOML Example" [owner] name = "Tom Preston-Werner" dob = 1979-05-27T07:32:00-08:00 # First class dates ``` -------------------------------- ### Importing strictyaml and ensure for parsing examples Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/without-a-schema.md Imports necessary classes and functions from the `strictyaml` library, including `Str`, `Any`, `MapPattern`, and `load`, along with `Ensure` for assertion-based testing in the Python parsing examples. ```python from strictyaml import Str, Any, MapPattern, load from ensure import Ensure ``` -------------------------------- ### Example SDLang Configuration Syntax Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/src/why-not/sdlang.md Demonstrates various SDLang features including single string values, multiple values, attributes, nested nodes, anonymous nodes, and matrix definitions. ```SDLang // This is a node with a single string value title "Hello, World" // Multiple values are supported, too bookmarks 12 15 188 1234 // Nodes can have attributes author "Peter Parker" email="peter@example.org" active=true // Nodes can be arbitrarily nested contents { section "First section" { paragraph "This is the first paragraph" paragraph "This is the second paragraph" } } // Anonymous nodes are supported "This text is the value of an anonymous node!" // This makes things like matrix definitions very convenient matrix { 1 0 0 0 1 0 0 0 1 } ``` -------------------------------- ### Example YAML document for line number extraction Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/what-line.md A sample YAML document used to demonstrate how `strictyaml` can extract line numbers and surrounding text for its elements. ```yaml y: p # Some comment a: | x # Another comment b: y c: a d: b ``` -------------------------------- ### Example StrictYAML Document Structure Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/src/why-not/toml.md Demonstrates a simple StrictYAML document, showcasing its concise syntax for maps and lists. This example highlights StrictYAML's design for readability and reduced syntactic noise compared to TOML, making it suitable for complex hierarchies. ```yaml # All about the character name: Ford Prefect age: 42 possessions: - Towel ``` -------------------------------- ### Example YAML snippet for `strictyaml` optional keys Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/compound/optional-keys-with-defaults.md This YAML snippet provides a basic example of input data used to demonstrate `strictyaml`'s handling of optional keys with default values. It contains a single key 'a' with an integer value. ```yaml a: 1 ``` -------------------------------- ### Define schema and load YAML snippet with strictyaml Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/what-line.md This snippet defines a `strictyaml` schema for the example YAML and loads the YAML content, preparing it for line number and context extraction. ```python from strictyaml import Map, Str, YAMLValidationError, load from ensure import Ensure schema = Map({"y": Str(), "a": Str(), "b": Str(), "c": Str(), "d": Str()}) snippet = load(yaml_snippet, schema) ``` -------------------------------- ### Define UniqueSeq Schema and Valid YAML Example Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/compound/sequences-of-unique-items.md Illustrates how to import `UniqueSeq` and `Str` from `strictyaml` to define a schema for a sequence of unique strings, alongside a valid YAML example. ```yaml - A - B - C ``` ```python from strictyaml import UniqueSeq, Str, load, as_document from ensure import Ensure schema = UniqueSeq(Str()) ``` -------------------------------- ### Example YAML Mapping Document Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/compound/mapping-yaml-object.md A simple YAML document demonstrating a mapping with three key-value pairs. ```yaml a: 1 b: 2 c: 3 ``` -------------------------------- ### Example YAML for StrictYAML Parsing Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/scalar/string.md A sample YAML document demonstrating various string types, including plain, boolean-like, unicode, and multi-line strings, intended for parsing by StrictYAML. ```yaml a: 1 b: yes c: â string d: | multiline string ``` -------------------------------- ### Get start line of YAML items including preceding comments Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/what-line.md Demonstrates how `strictyaml`'s `.start_line` property returns the starting line number of a YAML item, including any preceding comments associated with it. ```python Ensure(snippet["a"].start_line).equals(3) Ensure(snippet["d"].start_line).equals(9) ``` -------------------------------- ### Example YAML Document for StrictYAML Revalidation Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/revalidation.md A sample YAML document used throughout the examples, featuring 'capitals' and 'countries' sections to demonstrate multi-stage validation. ```yaml capitals: UK: 1 Germany: 2 countries: - Germany - UK ``` -------------------------------- ### Example YAML Data for Validation Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/label-exceptions.md A sample YAML document demonstrating a structure that will cause a validation error when processed by `strictyaml` due to a type mismatch. This snippet serves as the input for the subsequent Python validation example. ```yaml a: 1 b: - 1 - 2 ``` -------------------------------- ### Example YAML Snippet for StrictYAML Operations Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/roundtripping.md This YAML snippet serves as the base data for demonstrating loading, modification, and serialization operations with StrictYAML. It includes comments, nested structures, and a list. ```yaml # Some comment a: â # value comment # Another comment b: x: 4 y: 5 c: - a: 1 - b: 2 ``` -------------------------------- ### Get start and end line of entire YAML document Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/what-line.md Demonstrates how to obtain the overall starting and ending line numbers for the entire loaded YAML document by accessing `.start_line` and `.end_line` on the root `strictyaml` object. ```python Ensure(snippet.start_line).equals(1) Ensure(snippet.end_line).equals(10) ``` -------------------------------- ### Example StrictYAML Document Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/index.md A basic YAML document demonstrating the structure that StrictYAML can parse, featuring common data types like strings, integers, and lists. ```yaml # All about the character name: Ford Prefect age: 42 possessions: - Towel ``` -------------------------------- ### Import StrictYAML and Ensure libraries Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/compound/update.md Imports the necessary `strictyaml` library as `s` and the `ensure` library for assertions, commonly used in StrictYAML examples. ```python import strictyaml as s from ensure import Ensure ``` -------------------------------- ### Initial Loading of YAML with StrictYAML Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/revalidation.md Demonstrates the initial loading of the example YAML document using `strictyaml`. An `overall_schema` is applied, allowing flexible types for 'capitals' before more specific revalidation. ```python from strictyaml import Str, Int, Map, Seq, Any, load from ensure import Ensure overall_schema = Map({"capitals": Any(), "countries": Seq(Str())}) parsed = load(yaml_snippet, overall_schema) ``` -------------------------------- ### YAML Example Refactored Without Node Anchors Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/why/node-anchors-and-references-removed.md Shows the same data as the previous example but without using YAML node anchors or references, resulting in increased repetition but improved readability for non-programmers. ```yaml # sequencer protocols for Laser eye surgery --- - step: instrument: Lasik 2000 pulseEnergy: 5.4 pulseDuration: 12 repetition: 1000 spotSize: 1mm - step: instrument: Lasik 2000 pulseEnergy: 5.0 pulseDuration: 10 repetition: 500 spotSize: 2mm - step: instrument: Lasik 2000 pulseEnergy: 5.4 pulseDuration: 12 repetition: 1000 spotSize: 1mm - step: instrument: Lasik 2000 pulseEnergy: 5.0 pulseDuration: 10 repetition: 500 spotSize: 2mm - step: instrument: Lasik 2000 pulseEnergy: 5.4 pulseDuration: 12 repetition: 1000 spotSize: 2mm - step: instrument: Lasik 2000 pulseEnergy: 5.0 pulseDuration: 10 repetition: 500 spotSize: 2mm ``` -------------------------------- ### Example Output of Merged YAML Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/merge-yaml-documents.md This YAML block provides an example of the expected output after merging two YAML documents using `strictyaml`. It showcases how original comments are preserved and new values are integrated, demonstrating the final structure of the combined YAML. ```yaml # Some comment a: â # value comment # Another comment b: x: 8 # y is now 9 y: 9 c: - a: 1 - b: 2 ``` -------------------------------- ### Define StrictYAML Schema for Example Data Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/roundtripping.md This Python code defines the StrictYAML schema corresponding to the example YAML data. It specifies the expected types for 'a', 'b' (a nested map), and 'c' (an empty dictionary or a sequence of maps). ```python from strictyaml import Map, MapPattern, EmptyDict, Str, Seq, Int, load from ensure import Ensure schema = Map({ "a": Str(), "b": Map({"x": Int(), "y": Int()}), "c": EmptyDict() | Seq(MapPattern(Str(), Str())), }) ``` -------------------------------- ### Example YAML document for StrictYAML parsing Source: https://github.com/crdoconnor/strictyaml/blob/master/README.md A simple YAML document representing character data, including name, age, and a list of possessions. This document is used as the `yaml_snippet` input for subsequent Python parsing examples. ```yaml # All about the character name: Ford Prefect age: 42 possessions: - Towel ``` -------------------------------- ### StrictYAML: Structured Database Configuration Example Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/why-not/environment-variables-as-config.md This YAML snippet showcases how StrictYAML can clearly organize multiple database configurations hierarchically. It contrasts with the verbose environment variable approach, improving readability and significantly reducing the chance of errors by providing a structured view of related parameters. ```yaml database: personnel: host: xxx port: xxx name: xxx password: xxx factory: host: xxx port: xxx name: xxx password: xxx hotel backup: host: xxx name: xxx password: xxx hotel: host: xxx name: xxx port: xxx password: xxx ``` -------------------------------- ### Sample YAML data for strictyaml parsing Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/without-a-schema.md A multi-level YAML structure used as input for the subsequent Python parsing examples, demonstrating various scalar and mapping types. ```yaml a: x: 9 y: 8 b: 2 c: 3 ``` -------------------------------- ### Define Schema and Load YAML with StrictYAML Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/scalar/string.md Demonstrates how to define a StrictYAML schema using `Map` and `Str` types, and then load the example YAML snippet against this schema. This shows the initial parsing step, where all specified fields are expected to be strings. ```python from strictyaml import Str, Map, load from ensure import Ensure schema = Map({"a": Str(), "b": Str(), "c": Str(), "d": Str()}) parsed = load(yaml_snippet, schema) ``` -------------------------------- ### INI Configuration: Implicit String Typing Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/src/why/syntax-typing-bad.md Shows an INI configuration example where all values are implicitly treated as strings, as the format lacks explicit syntax for distinguishing data types like numbers. ```ini server=192.0.2.62 port=143 ``` -------------------------------- ### Get lines following a YAML item Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/what-line.md Shows how to use `strictyaml`'s `lines_after(x)` method to retrieve a specified number of lines immediately following a YAML item, providing additional context. ```python Ensure(snippet['a'].lines_after(4)).equals("b: y\nc: a\n\nd: b") ``` -------------------------------- ### Get lines preceding a YAML item Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/what-line.md Illustrates how to use `strictyaml`'s `lines_before(x)` method to retrieve a specified number of lines immediately preceding a YAML item, useful for context. ```python Ensure(snippet['a'].lines_before(1)).equals("# Some comment") ``` -------------------------------- ### Initial YAML Snippet and StrictYAML Imports Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/scalar/empty.md Defines the initial `yaml_snippet` with an empty value for key 'a' and imports necessary classes from the `strictyaml` library for subsequent validation and parsing examples. ```yaml a: ``` ```python from strictyaml import Map, Str, Enum, EmptyNone, EmptyDict, EmptyList, NullNone, load, as_document from ensure import Ensure ``` -------------------------------- ### YAML Example with Node Anchors and References Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/why/node-anchors-and-references-removed.md Demonstrates the use of YAML node anchors (`&id`) and references (`*id`) for deduplication, including the merge key (`<<:`) for partial overrides. This structure is presented as difficult for non-programmers to read. ```yaml # sequencer protocols for Laser eye surgery --- - step: &id001 # defines anchor label &id001 instrument: Lasik 2000 pulseEnergy: 5.4 pulseDuration: 12 repetition: 1000 spotSize: 1mm - step: &id002 instrument: Lasik 2000 pulseEnergy: 5.0 pulseDuration: 10 repetition: 500 spotSize: 2mm - step: *id001 # refers to the first step (with anchor &id001) - step: *id002 # refers to the second step - step: <<: *id001 spotSize: 2mm # redefines just this key, refers rest from &id001 - step: *id002 ``` -------------------------------- ### Example YAML Input for Decimal Parsing Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/scalar/decimal.md Demonstrates a YAML snippet containing decimal numbers, including one with high precision, suitable for parsing with StrictYAML's Decimal type. This snippet serves as the `yaml_snippet` variable used in subsequent Python examples. ```yaml a: 1.00000000000000000001 b: 5.4135 ``` -------------------------------- ### Example YAML snippet for Float parsing Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/scalar/float.md Demonstrates a basic YAML structure containing floating-point numbers, including a highly precise decimal and a standard float, to be parsed by StrictYAML. ```yaml a: 1.00000000000000000001 b: 5.4135 ``` -------------------------------- ### YAML Example for Datetime Validation Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/scalar/datetime.md Demonstrates various valid datetime formats that strictyaml can parse, including dates, datetimes with timezone offsets, and datetimes with 'Z' for UTC. ```YAML date: 2016-10-22 datetime1: 2016-10-22T14:23:12+00:00 datetime2: 2016-10-22T14:23:12Z datetime3: 20161022T14:23:12Z ``` -------------------------------- ### Example YAML Invoice Structure Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/what-is-yaml.md This YAML snippet demonstrates a typical invoice structure, showcasing key YAML features like associative data (receipt, date, customer), hierarchical data (customer details, address), and ordered lists (items). It also illustrates multi-line strings and various data types such as strings, numbers, and nested objects. ```yaml receipt: Oz-Ware Purchase Invoice date: 2012-08-06 customer: first name: Harry family name: Potter address: |- 4 Privet Drive, Little Whinging, England items: - part_no: A4786 description: Water Bucket (Filled) price: 1.47 quantity: 4 - part_no: E1628 description: High Heeled "Ruby" Slippers size: 8 price: 133.7 quantity: 1 ``` -------------------------------- ### Example YAML for Boolean Validation Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/scalar/boolean.md Defines a YAML structure with various string representations of boolean values, both true and false, to be used for testing the Bool validator's interpretation. ```yaml a: yes b: true c: on d: 1 e: True f: Y u: n v: False w: 0 x: Off y: FALSE z: no ``` -------------------------------- ### YAML Explicit Tag Example Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/src/why/explicit-tags-removed.md An example of an explicit type tag (`!!str`) applied to a YAML value, demonstrating how it would look in a script. StrictYAML's philosophy is to disable such tags, raising a `TagTokenDisallowed` exception if encountered. ```yaml - Don Corleone: Do you have faith in my judgment? - Clemenza: !!str Yes - Don Corleone: Do I have your loyalty? ``` -------------------------------- ### YAML Example for Invalid Datetime Input Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/scalar/datetime.md Provides a YAML snippet containing values that are not valid datetime formats, intended to demonstrate error handling during parsing by `strictyaml`. ```YAML date: 1 datetime1: â datetime2: b datetime3: c ``` -------------------------------- ### YAML Snippet with Duplicate Keys Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/restrictions/duplicate-keys.md This YAML example demonstrates a document containing the same key 'a' defined multiple times. StrictYAML will reject such documents to enforce uniqueness and prevent ambiguity. ```yaml a: cow a: bull ``` -------------------------------- ### TOML Syntax Typing Example Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/why-not/toml.md This TOML snippet demonstrates how data types like float and string are explicitly defined by the writer using syntax, such as quotes for strings. This approach can be confusing for non-programmers. ```toml flt2 = 3.1415 string = "hello" ``` -------------------------------- ### Example of Flow-Style YAML Syntax Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/src/why/flow-style-removed.md This snippet illustrates a basic example of flow-style YAML, where a mapping 'b' is defined using curly braces, mimicking JSON syntax, within a standard block-style YAML structure. This style is often criticized for hindering readability. ```yaml a: 1 b: {c: 3, d: 4} ``` -------------------------------- ### Parse YAML to Python Dictionary Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/scalar/boolean.md Demonstrates parsing the example YAML snippet using the defined schema and asserts that the resulting Python dictionary correctly maps the YAML boolean strings to Python boolean True or False values. ```python Ensure(load(yaml_snippet, schema)).equals({ "a": True, "b": True, "c": True, "d": True, "e": True, "f": True, "u": False, "v": False, "w": False, "x": False, "y": False, "z": False, }) ``` -------------------------------- ### Retrieve All Keys with .keys() Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/compound/mapping-yaml-object.md Shows how to use the `.keys()` method on a parsed YAML object to get a list of all keys, similar to a Python dictionary's keys. ```python Ensure(load(yaml_snippet, schema).keys()).equals(["a", "b", "c"]) ``` -------------------------------- ### Retrieve Line Numbers from StrictYAML Document (Python) Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/build-yaml-document.md Explains how to access the starting line number of a serialized YAML object using the `start_line` attribute, useful for debugging or positional awareness. ```python Ensure(yaml.start_line).equals(1) ``` -------------------------------- ### Standard YAML: Confusing Explicit/Implicit String Typing Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/src/why/syntax-typing-bad.md Illustrates the often confusing rules of Standard YAML regarding explicit string typing, showing examples where quotation marks are sometimes required and sometimes optional for string values. ```yaml a: text # not necessary b: "yes" # necessary c: "0" # necessary d: "3.5" # necessary e: in # not necessary f: out # not necessary g: shake it all about # not necessary h: "on" # necessary ``` -------------------------------- ### Example YAML Invoice Document Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/src/what-is-yaml.md This YAML snippet demonstrates the structure of an invoice, showcasing key YAML features such as key-value pairs, nested objects, ordered lists, and multi-line strings. It illustrates how YAML represents hierarchical and associative data, mapping directly to common data types like dictionaries and lists. ```yaml receipt: Oz-Ware Purchase Invoice date: 2012-08-06 customer: first name: Harry family name: Potter address: |- 4 Privet Drive, Little Whinging, England items: - part_no: A4786 description: Water Bucket (Filled) price: 1.47 quantity: 4 - part_no: E1628 description: High Heeled "Ruby" Slippers size: 8 price: 133.7 quantity: 1 ``` -------------------------------- ### CSV Data: Implicit String Typing Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/src/why/syntax-typing-bad.md Presents a CSV data example, highlighting that this format also lacks explicit syntax typing, requiring the consuming program to infer data types. ```csv server,port 192.0.2.62,143 ``` -------------------------------- ### Import StrictYAML for document modification and construction Source: https://github.com/crdoconnor/strictyaml/blob/master/README.md Re-imports necessary StrictYAML components, including `as_document`, which is used for constructing YAML documents from Python data structures, and redefines the schema for subsequent modification examples. ```python from strictyaml import load, Map, Str, Int, Seq, YAMLError, as_document schema = Map({"name": Str(), "age": Int(), "possessions": Seq(Str())}) ``` -------------------------------- ### Parse Flow Style YAML with dirty_load Method Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/restrictions/loading-dirty-yaml.md Illustrates how to parse a flow style YAML snippet using `strictyaml.dirty_load` with `allow_flow_style=True`. This example includes the YAML input and the Python assertion demonstrating the successful parsing against a defined schema. ```yaml foo: { a: 1, b: 2, c: 3 } y: {} z: [] ``` ```python assert dirty_load(yaml_snippet, schema, allow_flow_style=True) == {"foo": {"a": "1", "b": "2", "c": "3"}, "y": {}, "z": []} ``` -------------------------------- ### YAML Example with Node Anchors and References Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/src/why/node-anchors-and-references-removed.md This YAML snippet demonstrates the use of node anchors ('&id') and references ('*id') to deduplicate data. It shows how to define reusable blocks and refer to them, including merging ('<<: *id') and overriding specific keys. ```yaml # sequencer protocols for Laser eye surgery --- - step: &id001 # defines anchor label &id001 instrument: Lasik 2000 pulseEnergy: 5.4 pulseDuration: 12 repetition: 1000 spotSize: 1mm - step: &id002 instrument: Lasik 2000 pulseEnergy: 5.0 pulseDuration: 10 repetition: 500 spotSize: 2mm - step: *id001 # refers to the first step (with anchor &id001) - step: *id002 # refers to the second step - step: <<: *id001 spotSize: 2mm # redefines just this key, refers rest from &id001 - step: *id002 ``` -------------------------------- ### Example of Valid YAML Data for Email and URL Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/scalar/email-and-url.md This YAML snippet presents a valid data structure that conforms to the defined StrictYAML schema. It includes a correctly formatted email address for key 'a' and a complete URL for key 'b', demonstrating data that would pass validation. ```yaml a: billg@microsoft.com b: https://user:pass@example.com:443/path?k=v#frag ``` -------------------------------- ### Modify Single-line String in YAML with Multi-line Content Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/roundtripping.md This example first defines a YAML snippet with a single-line string and a multi-line string. It then defines a schema and uses Python to load the YAML, modify the single-line string 'a', and print the updated YAML, showing how `strictyaml` preserves the multi-line style for 'b'. ```yaml a: some b: | text ``` ```python schema = Map({"a": Str(), "b": Str()}) to_modify = load(yaml_snippet, schema) to_modify['a'] = 'changed' print(to_modify.as_yaml()) ``` ```yaml a: changed b: | text ``` -------------------------------- ### StrictYAML Schema-Driven Typing Example Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/why-not/toml.md This StrictYAML snippet illustrates how types are inferred from a schema, eliminating the need for explicit syntax like quotes. This approach reduces syntactic noise and improves readability, especially in complex documents. ```yaml flt2: 3.1415 string: hello ``` -------------------------------- ### Problem: Verbose Environment Variable Naming Conventions Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/why-not/environment-variables-as-config.md This example illustrates how the limitations of environment variables for structured data lead to verbose and error-prone naming conventions. It highlights the difficulty in spotting missing or incorrect variables when configuration parameters are flattened into long lists of individual environment variables. ```text PERSONNEL_DATABASE_HOST, PERSONNEL_DATABASE_PORT, PERSONNEL_DATABASE_NAME, PERSONNEL_DATABASE_PASSWORD, FACTORY_DATABASE_HOST, FACTORY_DATABASE_PORT, FACTORY_DATABASE_NAME, FACTORY_DATABASE_PASSWORD, HOTEL_BACKUP_DATABASE_HOST, HOTEL_BACKUP_DATABASE_USERNAME, HOTEL_BACKUP_DATABASE_PASSWORD, HOTEL_DATABASE_HOST, HOTEL_DATABASE_PORT, HOTEL_DATABASE_NAME, HOTEL_DATABASE_PASSWORD ``` -------------------------------- ### Parse YAML with StrictYAML (default string casting) Source: https://github.com/crdoconnor/strictyaml/blob/master/README.md Demonstrates the default parsing behavior of `strictyaml.load()` using the example YAML document. Without a schema, all scalar values are parsed as strings, and the result is a `YAML` object. ```python >>> load(yaml_snippet) YAML({'name': 'Ford Prefect', 'age': '42', 'possessions': ['Towel']}) ``` -------------------------------- ### YAML Example with Structured Schema for Deduplication Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/why/node-anchors-and-references-removed.md Illustrates an alternative YAML schema that separates step definitions from step usage, achieving deduplication and clarity without relying on node anchors. This approach refactors the document's structure for better interpretation. ```yaml step definitions: large: instrument: Lasik 2000 pulseEnergy: 5.4 pulseDuration: 12 repetition: 1000 spotSize: 1mm medium: instrument: Lasik 2000 pulseEnergy: 5.0 pulseDuration: 10 repetition: 500 spotSize: 2mm steps: - step: large - step: medium - step: large - step: medium - step: from: large except: spotSize: 2mm - step: large ``` -------------------------------- ### Parsing Basic Integers with StrictYAML Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/scalar/integer.md Demonstrates how to parse simple integer values from YAML using StrictYAML's `Int` schema type. It shows the basic setup of a schema and loading YAML content, followed by an assertion to verify the parsed output. The `yaml_snippet` variable refers to the preceding YAML block. ```yaml a: 1 b: 5 ``` ```python from strictyaml import Map, Int, load from ensure import Ensure schema = Map({"a": Int(), "b": Int()}) parsed = load(yaml_snippet, schema) ``` ```python Ensure(parsed).equals({"a": 1, "b": 5}) ``` -------------------------------- ### Example strictyaml.exceptions.YAMLValidationError Output Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/label-exceptions.md An illustration of the detailed error message produced by `strictyaml` when the provided YAML data fails to conform to the specified schema. This output clearly shows how the custom label 'myfilename' is integrated into the error path, aiding in quick identification of the problematic file or context. ```text strictyaml.exceptions.YAMLValidationError: when expecting a mapping in "myfilename", line 2, column 1: b: ^ (line: 2) found a sequence in "myfilename", line 4, column 1: - '2' ^ (line: 4) ``` -------------------------------- ### Example output of a StrictYAML YAMLError Source: https://github.com/crdoconnor/strictyaml/blob/master/README.md The detailed error message printed by StrictYAML when a schema violation occurs, specifically when a required key ('possessions') is not found. It includes line and column numbers for easy debugging. ```text while parsing a mapping in "", line 1, column 1: # All about the character ^ (line: 1) required key(s) 'possessions' not found in "", line 3, column 1: age: '42' ^ (line: 3) ``` -------------------------------- ### Validate YAML with StrictYAML Decimal Schema Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/scalar/decimal.md Demonstrates successful validation of the example `yaml_snippet` against the defined StrictYAML schema. This confirms that the parsed values are correctly interpreted as `decimal.Decimal` objects, maintaining their precision. ```python Ensure(load(yaml_snippet, schema)).equals({"a": Dec('1.00000000000000000001'), "b": Dec('5.4135')}) ``` -------------------------------- ### Validate MapPattern with Basic String-Integer Mapping (Equivalence 2) Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/compound/map-pattern.md Further demonstrates validating a YAML snippet against the `MapPattern` schema. This example uses different string keys, confirming the schema's flexibility with arbitrary key names. ```yaml a: 1 c: 3 ``` ```python Ensure(load(yaml_snippet, schema)).equals({"a": 1, "c": 3}) ``` -------------------------------- ### Example of Flow-Style YAML Syntax Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/why/flow-style-removed.md Demonstrates a simple YAML structure where a mapping 'b' uses flow-style (JSON-like curly braces) to define its key-value pairs 'c' and 'd'. This style is criticized for hampering readability. ```yaml a: 1 b: {c: 3, d: 4} ``` -------------------------------- ### StrictYAML Schema-Based Type Inference Example Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/src/why-not/toml.md This StrictYAML snippet shows how types are inferred from a schema, eliminating the need for explicit syntax like quotes for strings. The schema acts as the single source of truth for type information, which significantly reduces syntactic noise in larger documents. ```yaml flt2: 3.1415 string: hello ``` -------------------------------- ### Structured Representation of LS_COLORS Data with StrictYAML Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/src/why-not/environment-variables-as-config.md This snippet demonstrates how StrictYAML can represent the same LS_COLORS data in a more readable, hierarchical YAML format. It shows how comments can be used to explain cryptic codes, significantly improving clarity and maintainability compared to a single, unstructured string. ```yaml # Special di: 01;34 # directory is blue # Extensions *.tz: 01;31 # red *.flv: 01;35 # purple ``` -------------------------------- ### TOML Syntax Typing Example Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/src/why-not/toml.md This TOML snippet demonstrates how data types like float and string are explicitly defined using syntax (e.g., quotes for strings, decimal for floats). The writer of the markup decides the type, which can be confusing for non-programmers. ```toml flt2 = 3.1415 string = "hello" ``` -------------------------------- ### Example of Duplicate Keys in YAML Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/why/duplicate-keys-disallowed.md This YAML snippet demonstrates a mapping where the key 'x' is defined multiple times. While standard YAML parsers will process this, typically using the last value ('bull'), StrictYAML will throw a DuplicateKeysDisallowed exception to prevent ambiguity and potential user errors. ```YAML x: cow y: dog x: bull ``` -------------------------------- ### Get lines of a YAML item including surrounding comments Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/what-line.md Demonstrates how `strictyaml`'s `lines()` method can extract the full text of a YAML item, including its own content and any associated comments that are part of its block. ```python print(load(yaml_snippet, schema)['a'].lines()) ``` ```yaml a: | x # Another comment ``` -------------------------------- ### Demonstrate Disallowed Node Anchors and References in YAML Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/restrictions/disallowed-yaml.md This snippet illustrates YAML content using node anchors (`&`) and references (`*`), which are disallowed by StrictYAML. It includes the YAML content, the Python code to attempt loading it, and the resulting `AnchorTokenDisallowed` exception output. ```yaml x: a: &node1 3.5 b: 1 c: *node1 ``` ```python load(yaml_snippet, schema, label="disallowed") ``` ```python strictyaml.exceptions.AnchorTokenDisallowed: While scanning in "disallowed", line 2, column 6: a: &node1 3.5 ^ (line: 2) Found confusing disallowed anchor token (surround with ' and ' to make text appear literally) in "disallowed", line 2, column 12: a: &node1 3.5 ^ (line: 2) ``` -------------------------------- ### Parsing YAML with NaN (Not a Number) values Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/scalar/float.md Provides YAML examples of `nan` and `.NaN` representations. The accompanying Python code demonstrates how StrictYAML parses these into Python's `float('nan')` and verifies them using `math.isnan`. ```yaml a: nan b: .NaN ``` ```python Ensure(isnan(load(yaml_snippet, schema)["a"].data)).is_true() Ensure(isnan(load(yaml_snippet, schema)["b"].data)).is_true() ``` -------------------------------- ### Handle StrictYAML parsing errors with try-except block Source: https://github.com/crdoconnor/strictyaml/blob/master/README.md Shows how to use a `try-except` block to catch `YAMLError` exceptions that occur during parsing when the YAML content (e.g., the 'missing key' example) violates the defined schema or has syntactic problems. The error message provides details about the violation. ```python try: person = load(yaml_snippet, schema) except YAMLError as error: print(error) ``` -------------------------------- ### Validate MapPattern with Float Keys and Integer Values Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/compound/map-pattern.md Illustrates using `MapPattern` with `Float` keys and `Int` values. The example validates a YAML snippet where keys are floating-point numbers, demonstrating the schema's type flexibility. ```yaml 10.25: 23 20.33: 76 ``` ```python Ensure(load(yaml_snippet, MapPattern(Float(), Int())).data).equals({10.25: 23, 20.33: 76}) ``` -------------------------------- ### Validate MapCombined with Optional and Undefined Keys Present Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/compound/map-combined.md This example demonstrates successful parsing of YAML data where both an optional key (`foo`) and an undefined key (`bar`) are present, conforming to the `MapCombined` schema. The Python assertion verifies the parsed data. ```yaml required: Hello World foo: 42 bar: 42 ``` ```python Ensure(load(yaml_snippet, schema).data).equals( { "required": "Hello World", "foo": 42, "bar": "42", } ) ``` -------------------------------- ### Using Float as a YAML map key Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/scalar/float.md Illustrates how to define a StrictYAML schema where floating-point numbers can serve as keys in a YAML map. The example shows serialization of a Python dictionary with float keys and subsequent access to values using these keys. ```python document = as_document(OrderedDict([("3.5", "a"), ("2.1", "c")]), MapPattern(Float(), Str())) print(document.data[3.5]) print(document.data[2.1]) ``` ```text a c ``` -------------------------------- ### Example YAML for `strictyaml` Map with Custom Key Validator Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/compound/mapping-with-slug-keys.md A YAML snippet illustrating the data structure that can be validated by a `strictyaml` Map schema using a custom key validator. Keys like 'Name' and 'DIAL CODE' will be transformed during validation. ```yaml Name: United Kingdom country-code: GB DIAL CODE: +44 official languages: - English - Welsh ``` -------------------------------- ### Get end line of YAML items including trailing comments Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/what-line.md Illustrates how `strictyaml`'s `.end_line` property returns the ending line number of a YAML item, including any trailing comments that are part of its block. ```python Ensure(snippet["a"].end_line).equals(6) Ensure(snippet["d"].end_line).equals(10) ``` -------------------------------- ### Example: Complex String Substructure in LS_COLORS Environment Variable Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/why-not/environment-variables-as-config.md This snippet shows how complex configuration data is encoded into a single, cryptic string within the LS_COLORS environment variable. It highlights the limitations of simple key-value pairs for structured information, leading to hard-to-read values. ```shell rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36: ``` -------------------------------- ### Python Validation and Assertion of `strictyaml` Map Data Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/compound/mapping-with-slug-keys.md Loads the previously defined `yaml_snippet` (the example YAML data) against the `strictyaml` schema and asserts that the resulting Python dictionary matches the expected structure, confirming the successful application of the custom key validator and key transformation. ```python Ensure(load(yaml_snippet, schema).data).equals( { "name": "United Kingdom", "country-code": "GB", "dial-code": "+44", "official-languages": ["English", "Welsh"], } ) ``` -------------------------------- ### Hierarchical Database Configuration with StrictYAML Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/src/why-not/environment-variables-as-config.md This snippet illustrates how StrictYAML can structure multiple database configurations hierarchically. This approach makes configurations easier to read, manage, and significantly reduces the potential for errors that often arise from flat, verbose environment variable lists. ```yaml database: personnel: host: xxx port: xxx name: xxx password: xxx factory: host: xxx port: xxx name: xxx password: xxx hotel backup: host: xxx name: xxx password: xxx hotel: host: xxx name: xxx port: xxx password: xxx ``` -------------------------------- ### StrictYAML Implicit String Typing Example Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/why/syntax-typing-bad.md This StrictYAML snippet illustrates a design where all values are implicitly treated as strings unless a schema explicitly dictates otherwise. This approach prioritizes terseness by avoiding quotation marks for most string values, relying on an external schema for type enforcement. ```yaml server: 192.0.2.62 port: 143 ``` -------------------------------- ### Example of Invalid YAML Data for Email and URL Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/scalar/email-and-url.md This YAML snippet provides an example of data that intentionally violates the defined StrictYAML schema. The values for 'a' and 'b' are not valid email addresses or URLs, respectively, which is expected to trigger a validation error. ```yaml a: notanemail b: notaurl ``` -------------------------------- ### Demonstrate Disallowed Flow Style Sequence in YAML Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/restrictions/disallowed-yaml.md This snippet illustrates a YAML flow style sequence, which is not permitted by StrictYAML. It includes the YAML content, the Python code to attempt loading it, and the resulting `FlowMappingDisallowed` exception output. ```yaml [a, b]: [x, y] ``` ```python load(yaml_snippet, schema, label="disallowed") ``` ```python strictyaml.exceptions.FlowMappingDisallowed: While scanning in "disallowed", line 1, column 1: [a, b]: [x, y] ^ (line: 1) Found ugly disallowed JSONesque flow mapping (surround with ' and ' to make text appear literally) in "disallowed", line 1, column 2: [a, b]: [x, y] ^ (line: 1) ``` -------------------------------- ### Applying partial schema with MapPattern and Any in strictyaml Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/howto/without-a-schema.md Illustrates how to apply a partial schema using `MapPattern(Str(), Any())` to enforce string keys at the top level while allowing flexible values for the corresponding entries, showcasing a hybrid approach to schema validation for `yaml_snippet`. ```python Ensure(load(yaml_snippet, MapPattern(Str(), Any()))).equals({"a": {"x": "9", "y": "8"}, "b": "2", "c": "3"}) ``` -------------------------------- ### StrictYAML YAMLValidationError Traceback Example Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/using/alpha/scalar/email-and-url.md This snippet displays the traceback of a `strictyaml.exceptions.YAMLValidationError` that occurs when invalid data is loaded. It highlights the specific error message ('when expecting an email address found non-matching string') and the exact location in the YAML where the validation failed. ```python strictyaml.exceptions.YAMLValidationError: when expecting an email address found non-matching string in "", line 1, column 1: a: notanemail ^ (line: 1) ``` -------------------------------- ### Preparing for YAML Document Modification Source: https://github.com/crdoconnor/strictyaml/blob/master/docs/public/index.md Sets up the environment by importing necessary `strictyaml` components, including `as_document` for creating YAML objects from Python data, and defines the schema for subsequent operations. ```python from strictyaml import load, Map, Str, Int, Seq, YAMLError, as_document schema = Map({"name": Str(), "age": Int(), "possessions": Seq(Str())}) ```