Parsing comma separated items (CommaSeparated)

Comma-separated values can be validated and parsed using the CommaSeparated validator.

Note that the space following the commas is stripped by default when parsed.

from strictyaml import CommaSeparated, Int, Str, Map, load, as_document
from ensure import Ensure

int_schema = Map({"a": CommaSeparated(Int())})

str_schema = Map({"a": CommaSeparated(Str())})

Parse as int:

a: 1, 2, 3
Ensure(load(yaml_snippet, int_schema)).equals({"a": [1, 2, 3]})

Parse as string:

a: 1, 2, 3
Ensure(load(yaml_snippet, str_schema)).equals({"a": ["1", "2", "3"]})

Invalid int comma separated sequence:

a: 1, x, 3
load(yaml_snippet, int_schema)
strictyaml.exceptions.YAMLValidationError:
when expecting an integer
  in "<unicode string>", line 2, column 1:
    
    ^ (line: 2)
found arbitrary text
  in "<unicode string>", line 1, column 1:
    a: 1, x, 3
     ^ (line: 1)

Serialize list to comma separated sequence:

print(as_document({"a": [1, 2, 3]}, int_schema).as_yaml())
a: 1, 2, 3

Serialize valid string to comma separated sequence:

print(as_document({"a": "1,2,3"}, int_schema).as_yaml())
a: 1,2,3

Serialize invalid string to comma separated sequence:

print(as_document({"a": "1,x,3"}, int_schema).as_yaml())
strictyaml.exceptions.YAMLSerializationError:
'x' not an integer.

Attempt to serialize neither list nor string raises exception:

as_document({"a": 1}, int_schema)
strictyaml.exceptions.YAMLSerializationError:
expected string or list, got '1' of type 'int'

Executable specification

Page automatically generated from commaseparated.story.