Definitions

type converter

A type converter function that converts a textual representation
of a value type into instance of this value type.
In addition, a type converter function is often annotated with attributes
that allows the parse module to use it in a generic way.
A type converter is also called a parse_type (a definition used here).

cardinality field

A naming convention for related types that differ in cardinality.
A cardinality field is a type name suffix in the format of a field.
It allows parse format expression, ala:

# -- USE CASE: Use the type converter with the parse module.schema="Hello {number:Number}"parser=parse.Parser(schema,dict(Number=parse_number))result=parser.parse("Hello 42")assertresultisnotNone,"REQUIRE: text matches the schema."assertresult["number"]==42result=parser.parse("Hello XXX")assertresultisNone,"MISMATCH: text does not match the schema."

Hint

The described functionality above is standard functionality
of the parse module. It serves as introduction for the remaining cases.

Cardinality

Create an type converter for “ManyNumbers” (List, separated with commas)
with cardinality “1..* = 1+” (many) from the type converter for a “Number”.

# -- USE CASE: Create new type converter with a cardinality constraint.# CARDINALITY: many := one or more (1..*)fromparseimportParserfromparse_typeimportTypeBuilderparse_numbers=TypeBuilder.with_many(parse_number,listsep=",")schema="List: {numbers:ManyNumbers}"parser=Parser(schema,dict(ManyNumbers=parse_numbers))result=parser.parse("List: 1, 2, 3")assertresult["numbers"]==[1,2,3]

Create an type converter for an “OptionalNumbers” with cardinality “0..1 = ?”
(optional) from the type converter for a “Number”.