KDL-py
A handwritten Python 3.12+ implementation of a parser
for the KDL Document Language,
fully compliant with KDL 2.0.0,
with automatic fallback support for parsing legacy KDL 1.0.0 documents
(see ParseConfig.version).
Printing always produces valid KDL 2.0.0.
KDL is, as the name suggests, a document language, filling approximately the same niche as JSON/YAML/XML/etc to be a simple but powerful language for config files. It combines the best of several of these languages, while avoiding their pitfalls: more general than JSON and more powerful than XML, while avoiding the verbosity of XML or the explosive complexity of YAML.
kdl-py, in particular, is focused on ease-of-use, supporting things like date/times, ip addresses, urls, uuids, regexes, and binary data directly in your KDL document (via powerful but simple tagged values), and parsing them into native Python types automatically, or doing the reverse and letting you build KDL document trees with these values directly, and automatically and safely serializing them into KDL text for later parsing!
You can customize parsing and serialization further for your application very easily,
by providing node or value "converters"
to turn plain KDL values or nodes
into application-specific types,
and then turning them back into KDL text automatically
merely by adding a .to_kdl() method to your classes.
Installing
pipx install kdl-py
When installed, a kdlreformat command-line program is also made available,
which can canonicalize a KDL document. See below for options.
Using
The kdl.parse(str, parseConfig|None) function parses, you guessed it, a string of KDL into a KDL document object:
>>> import kdl
>>> doc = kdl.parse('''
... node_name arg {
... child_node foo=1 bar=#true
... }
... ''')
>>>
>>> doc
Document(
nodes=[
Node(
name='node_name',
tag=None,
args=['arg'],
props={},
nodes=[
Node(
name='child_node',
tag=None,
args=[],
props={
'foo': 1.0,
'bar': True
},
nodes=[]
)
]
)
],
printConfig=None
)
You can also create a kdl.Parser() object and call its .parse() method; Parser objects can set up parsing and printing options that'll apply by default. See below for how to configure parsing options.
Either way, you'll get back a kdl.Document object, which is fully mutable. By default, untagged KDL values are represented with native Python objects.
>>> doc.nodes[0].nodes[0].props["foo"] = 2
>>>
>>> print(doc)
node_name arg {
child_node foo=2 bar=#true
}
Stringifying a kdl.Document object will produce a valid KDL 2.0 document back. You can also call doc.print(printConfig|None) to customize the printing with a PrintConfig object, described below.
Inserting Native Values
kdl-py allows a number of native Python objects to be used directly in KDL documents by default, and allows you to customize your own objects for use.
kdl-py automatically recognizes and correctly serializes the following objects:
bool: as untagged#trueor#falseNone: as untagged#nullint,float: as untagged decimal number (or#inf,#-inf,#nanfor non-finite floats)str: as untagged string (bare identifier when valid in KDL 2.0, otherwise quoted string)bytes: as(base64)-tagged stringdecimal.Decimal: as(decimal)-tagged stringdatetime,date, andtime: as(date-time),(date), or(time)-tagged stringsipaddress.IPv4Addressandipaddress.IPv6Address: as(ipv4)or(ipv6)-tagged stringsurllib.parse.ParseResult(the result of callingurllib.parse.urlparse()): as(url)-tagged stringuuid.UUID: as(uuid)-tagged stringre.Pattern(the result of callingre.compile()on astr): as(regex)-tagged raw string (#"..."#). Must not have non-default external flags (such asre.IGNORECASEpassed tore.compile()); use inline flags in the pattern string (such as(?i)) instead, otherwise serialization raises aValueError.
All of the tags used above are reserved and predefined by the KDL specification.
In addition, any object with a .to_kdl() method
can be used in a kdl-py document.
The method will be called when the document is stringified:
when used as a value, it must return one of the kdl-py Value types
or any of the native types defined above;
when used in a node list (doc.nodes or node.nodes), it must return a kdl.Node.
(For parsing KDL into these native types,
or your own types,
see the ParseConfig section, below.)
Customizing Parsing
Parsing can be controlled via a kdl.ParseConfig object,
which can be provided in three ways.
In order of importance:
- Passing a
ParseConfigobject tokdl.parse(str, ParseConfig|None)orparser.parse(str, ParseConfig|None)(if you've constructed akdl.Parser). - Creating a
kdl.Parser(parseConfig|None, printConfig|None), which automatically applies it to its.parse()method if not overridden. - Fiddling with the
kdl.parsing.defaultsobject, which is used if nothing else provides a config.
A ParseConfig object has the following properties:
-
nativeUntaggedValues: bool = TrueControls whether the parser produces native Python objects (
str,int,floatincludinginf/-inf/nan,bool,None) when parsing untagged values (those without a(foo)prefix), or always produces kdl-py objects (such askdl.String,kdl.Decimal,kdl.Infinity,kdl.NaN, etc). -
nativeTaggedValues: bool = TrueControls whether the parser produces native Python objects when parsing tagged values, for KDL's reserved type annotations:
i8,i16,i32,i64,i128,u8,u16,u32,u64,u128,isize,usizeon numbers: Checks that the value is an integer in the specified range (isize/usizeuse the current Python platform's pointer width viasys.maxsize), raisingParseErroron out-of-range or fractional values, then converts it to anint. (It will serialize back out as an ordinary untagged number.)f32,f64on numbers: Converts it to afloat. (It will serialize back out as an ordinary untagged number.)decimal64,decimal128on numbers, anddecimalon strings: Converts it to adecimal.Decimalobject. (Always reserializes to a(decimal)-tagged string.)date-time,date,timeon strings: Converts to adatetime,date, ortimeobject.ipv4,ipv6on strings: Converts it to anipaddress.IPv4Addressoripaddress.IPv6Addressobject.url,url-reference,irl,irl-referenceon strings: Converts it to aurllib.parse.ParseResulttuple. (Always reserializes to a(url)-tagged string.)uuidon strings: Converts it to auuid.UUIDobject.regexon strings: Converts it to are.Patternobject. (It will serialize back out as a(regex)-tagged raw string.)base64on strings: Converts it to abytesobject using standard Base64 decoding.base85on strings: Converts it to abytesobject using Ascii85 decoding (both plain and Adobe<~...~>-delimited). (Reserializes to a(base64)-tagged string.)
The remaining KDL reserved string annotations do not have an appropriate native type or validator in the Python standard library, so kdl-py leaves them as tagged
kdl.Stringobjects (you can handle them via customvalueConvertersif needed):duration: Python'sdatetime.timedeltacannot represent ISO 8601 calendar years or months and has no ISO 8601 duration parser.currency,country-2,country-3,country-subdivision: no built-in ISO 4217 or ISO 3166 types or code tables.email,idn-email: no standard-library RFC 5322 / RFC 6531 email address value type.hostname,idn-hostname: no standard-library RFC 1123 / RFC 5890 hostname type.url-template: no standard-library RFC 6570 URI Template parser or type.
-
valueConverters: dict[ValueKey, Callable] = {}A dictionary of ValueKey->converter functions, letting you parse values (like
(date)"2021-01-01") into whatever types you'd like.Whenever the parser encounters a value, it will attempt to find an entry in this dict whose
ValueKeymatches the value. If it succeeds, it will call the associated converter function with two arguments: the fully-constructed kdl-py object, and aParseFragmentobject giving you access to the precise characters parsed from the document (for the value; the tag, if any, won't be included, as you can get it from the object itself). Whatever you return will be inserted into the document instead of the originally-parsed value.You can produce KDL values (such as parsing
(hex)"0x12.e5"into akdl.Decimal, since KDL doesn't support fractional hex values), or produce any other Python type. If you return a non-KDL type, you probably want to ensure it has a.to_kdl()method (or is one of the supported built-in types), so it can be serialized back into a KDL document.Note that only one conversion can happen to a given value. Your converters are checked in the dictionary's iteration order, then if none of them succeeded it will attempt to run the
nativeUntaggedValuesornativeTaggedValuesbehaviors, if they're turned on. If a converter returnsNotImplemented, it will continue looking for a matching converter. -
nodeConverters: dict[NodeKey, Callable] = {}Similar to
valueConverters, except it usesNodeKeys, and it convertskdl.Nodes instead.There is no native conversion of nodes; if none of your converters successfully run, the node will be inserted as-is.
-
version: Literal[1, 2, "auto"] = "auto"Controls which KDL grammar version to parse with. By default (
"auto"), the parser parses as KDL 2.0, respecting any leading/- kdl-version 1or/- kdl-version 2version marker, and opportunistically falls back to KDL 1.0 (viakdl.kdl1) if a KDL 2.0 parse error looks like a KDL 1.0 construct (such as unprefixedtrue/false/nullkeywords,r"..."/r#"..."#raw strings, multiline single-quoted strings,\/escapes, or KDL 1.0 bare identifiers). A leading/- kdl-version 2marker disables KDL 1.0 fallback; if fallback is attempted and also fails, the original KDL 2.0ParseErroris raised.Set
version=2for strict KDL 2.0 parsing, orversion=1to parse strictly as KDL 1.0 (an explicit1or2overrides any/- kdl-versionmarker in the document; any other value raisesValueError). KDL 1.0 documents parse into the exact sameDocument/Node/Valuestructure, respecting all the sameParseConfigoptions and converters, and serialize back out as valid KDL 2.0.
ParseFragment
kdl.ParseFragment is passed to your custom converters,
specified in kdl.ParseConfig.valueConverters and kdl.ParseConfig.nodeConverters,
giving you direct access to the input characters
before any additional processing was done on them.
This is useful, for example,
to handle numeric types
that might have lost precision in the normal parse.
It exposes a .fragment property,
containing the raw text of the value
(after the tag, if any) for value converters,
or the raw text of the node's tag (if any) and name for node converters.
It also exposes a .error(str) method,
which takes a custom error message
and returns a kdl.ParseError
with the ParseFragment's location already built in,
ready for you to raise.
This should be used if your conversion fails for any reason,
so your errors look the same as native parse errors.
Customizing Printing
Like parsing, printing a kdl-py Document back to a KDL 2.0 string can be controlled by a kdl.PrintConfig object,
which can be provided in three ways.
In order of importance:
- Passing a
PrintConfigobject todoc.print(PrintConfig|None). - Setting
doc.printConfigto aPrintConfig. (This is done automatically for any documents produced by aParser, if you pass theprintConfigoption to the constructor.) - Fiddling with the
kdl.printing.defaultsobject, which is used if nothing else provides a config.
A PrintConfig object has the following properties:
-
indent: str = "\t"The string used for each indent level. Defaults to tabs, but can be set to a sequence of spaces if desired (or anything else).
-
semicolons: bool = FalseWhether or not nodes are ended with semicolons. (The printer always ends nodes with a newline anyway, so this is purely a stylistic choice.)
-
printNullArgs: bool = TrueWhen
False, automatically skips over any#null/Nonearguments. This will corrupt documents that use the#nullkeyword intentionally, but can be useful if you'd prefer to use aNonevalue as a signal that the argument has been removed. -
printNullProps: bool = TrueIdentical to
printNullArgs, but applies to properties rather than arguments. -
respectStringType: bool | Literal["auto"] = "auto"Controls how string values (as well as native Python
strvalues, node names, property keys, and tags) are formatted in KDL 2.0 output:"auto"(default): preserveskdl.RawStringvalues as raw strings (falling back to escaped quoted strings if the value can't be printed as a single-line raw string). For all other strings (kdl.IdentString,kdl.String, nativestr, node names, property keys, and tags), picks the cleanest representation in order:- bare identifier string if valid in KDL 2.0,
- normal quoted string if it contains no characters requiring escapes,
- single-line raw string (
#"..."#) if representable without escapes, - quoted string with escapes as a final fallback.
True: preserves each string's exact type as much as reasonably possible:kdl.IdentString(as well as native Pythonstrvalues, node names, property keys, and tags) outputs as a bare identifier when valid in KDL 2.0, falling back to a quoted string otherwisekdl.RawStringoutputs as a raw string (falling back to quoted if manually constructed to not be a valid single-line raw string)kdl.Stringalways outputs as a normal quoted string
False: ignores input string types and always prints bare identifiers when valid in KDL 2.0, or normal quoted strings otherwise (never raw strings).
-
respectRadix: bool = TrueSimilar to
respectStringType, whenTruethe printer will output numbers as the radix they were in the input, like0x1bfor hex numbers. WhenFalse, the printer always outputs decimal numbers.Again, this only has an effect on kdl-py objects; native Python numbers are printed as normal for Python.
-
exponent: str = "e"What character to use for the exponent part of decimal numbers, when printed with scientific notation. Should only be set to "e" or "E".
Like the previous options, this only has an effect on kdl-py objects; native Python numbers are printed as normal for Python.
-
sortProperties: bool = FalseWhen
False, a node's properties are printed in insertion order. WhenTrue, properties are printed sorted lexicographically by key.
Full API Reference
-
kdl.parse(str, config: kdl.ParseConfig|None) -> kdl.Document -
kdl.Parser(parseConfig: kdl.ParseConfig|None, printConfig: kdl.PrintConfig|None)parser.parse(str, config: kdl.ParseConfig|None) -> kdl.Document
-
kdl.Document(nodes: list[kdl.Node]?, printConfig: kdl.PrintConfig|None)doc.print(PrintConfig|None) -> strdoc[NodeKey] -> Nodereturns the first child node matching theNodeKey. Raises aKeyErrorif nothing matches theNodeKey, similar to adict.doc.get(NodeKey, default: T = None) -> kdl.Node | Treturns the first child node matching theNodeKey. Returns the default value if nothing matches.doc.getAll(NodeKey) -> Iterable[kdl.Node]returns all child nodes matching theNodeKey
-
kdl.Node(name: str, tag: str|None = None, args: list[Any]?, props: dict[str, Any]?, nodes: list[kdl.Node]?)node.print(PrintConfig|None = None, indentLevel: int = 0) -> strnode[NodeKey] -> Nodereturns the first child node matching theNodeKey. Raises aKeyErrorif nothing matches theNodeKey, similar to adict.node.get(NodeKey, default: T = None) -> kdl.Node | Treturns the first child node matching theNodeKey. Returns the default value if nothing matches.node.getAll(NodeKey) -> Iterable[kdl.Node]returns all child nodes matching theNodeKeynode.matchesKey(NodeKey) -> boolreturns whether the node matches theNodeKeynode(key: int|str) -> Any/node.getEntry(key: int|str, default = UNSET) -> Any: (Note: that is, the node is callable directly, asnode(0)ornode("prop").) Gets an argument byintindex (fromnode.args) or a property bystrkey (fromnode.props). If the index/key is missing, returnsdefaultwhen provided (in.getEntry(), only), or raisesIndexError/KeyErrorotherwise. Passing aboolor other non-int/strkey raisesTypeError.node.setEntry(key: int|str, value: Any) -> None: sets an argument byintindex (appending ifkey == len(node.args), raisingIndexErrorif out of range) or sets/inserts a property bystrkey. Passing aboolor other non-int/strkey raisesTypeError.node.getProps(ValueKey) -> Iterable[tuple[str, Any]]returns an iterator of(name, value)pairs for the properties whose value matches theValueKey(Note: for this purpose, non-KDL values, such asint, have no tag, and can only meaningfully be tested via aTypeKey.)node.getArgs(ValueKey) -> Iterable[Any]returns an iterator of the arguments that match theValueKey(Same disclaimer as.getProps().)
-
kdl.Value‡val.print(PrintConfig|None) -> strval.matchesKey(ValueKey) -> boolreturns whether the value matches theValueKey
-
kdl.Binary(value: int, tag: str|None = None) -
kdl.Octal(value: int, tag: str|None = None) -
kdl.Decimal(mantissa: int|float, exponent: int = 0, tag: str|None = None)dec.value: readonlyfloat,float(mantissa)whenexponent == 0or parsed fromf"{mantissa}e{exponent}"
-
kdl.Hex(value: int, tag: str|None = None) -
kdl.Infinity(value: float, tag: str|None = None) -
kdl.NaN(value: float = float("nan"), tag: str|None = None) -
kdl.Bool(value: bool, tag: str|None = None) -
kdl.Null(tag: str|None = None)null.value: readonly, alwaysNone
-
kdl.IdentString(value: str, tag: str|None = None) -
kdl.RawString(value: str, tag: str|None = None) -
kdl.String(value: str, tag: str|None = None) -
kdl.ExactValue(chars: str, tag: str|None = None)† -
kdl.Numberish,kdl.Stringish‡ -
kdl.ParseConfig(...)see above for optionskdl.parsing.defaults: defaultParseConfig
-
kdl.PrintConfig(...)see above for optionskdl.printing.defaults: defaultPrintConfig
-
kdl.ParseError: thrown for all parsing errorserror.msg: str: hopefully informativeerror.line: int: 1-indexederror.col: int: 1-indexed
-
kdl.ParseFragment: passed to converter functionspf.fragment: slice from the source stringpf.error(msg: str)returns akdl.ParseErrorwith error location set properly already
-
kdl.nodeMatchesKey(val: Any, key: kdl.NodeKey) -> bool -
kdl.valueMatchesKey(val: Any, key: kdl.ValueKey) -> bool -
kdl.tagMatchesKey(val: str|None, key: kdl.TagKey) -> bool -
kdl.nameMatchesKey(val: str|None, key: kdl.NameKey) -> bool -
kdl.typeMatchesKey(val: Any, key: kdl.TypeKey) -> bool- Functions implementing the tag/name/type matching
used by the
node.matchesKey()andvalue.matchesKey()methods, in case you want to use the same filtering yourself.
- Functions implementing the tag/name/type matching
used by the
† Not produced by the parser.
Can be returned by a user's .to_kdl() method
if they want to produce a value precisely in a particular syntax,
in a way that the built-in kdl-py classes don't.
‡ Not produced by the parser.
These are base classes to help in type testing:
Value matches all value classes,
Numberish matches all six numeric value classes (Binary, Octal, Decimal, Hex, Infinity, NaN),
and Stringish matches all three string value classes (IdentString, String, RawString).
A few type aliases also exist, used by the module in a few places and potentially useful for your code:
kdl.KDLAny: aDocument,Node, or any of theValuesubtypeskdl.KDLValue: any of theValuesubtypeskdl.KDLishValue: aKDLValueor one of the supported Python native types (see "Inserting Native Values")kdl.ParseVersion:Literal[1, 2, "auto"], the type forParseConfig.versionkdl.StringTypeMode:bool | Literal["auto"], the type forPrintConfig.respectStringTypekdl.ValueKey,kdl.NodeKey,kdl.TagKey,kdl.NameKey,kdl.TypeKey: the types forValueKeys andNodeKeys (and their individual pieces)
These aliases only exist when typing.TYPE_CHECKING is true,
so they're only useful for writing types;
they won't be visible at runtime.
NodeKey
A few data structures and functions take a NodeKey
to match against a node,
based on its name and/or tag.
A NodeKey is either a NameKey or a (TagKey, NameKey) tuple,
matching against the node's name and/or tag.
NameKeys and TagKeys can be:
None: When matched against a tag, only succeeds against aNonetag (aka a tagless node likefoo). When matched against a name, automatically succeeds, since nodes are guaranteed to have a name....: Always succeeds. Use this when, say, you want to match against a particular tag, regardless of the nodename, like("my-tag", ...).- a
str: Succeeds if the tag/name is that exact string. - a
re.Pattern(a regex, such asre.compile(r".*foo")): Succeeds if the regex matches the tag/name. Note that this uses.match()semantics, automatically anchoring against the start of the string; prepend your regex with.*?if you want it to match anywhere. - a function, taking a
str | Noneand returning abool: Succeeds if the function, when called with the tag/name, returns True.
So, for example,
doc.getAll("foo") would return all nodes whose name is "foo",
regardless of tag.
doc.getAll(("my-tag", ...)) would return all nodes whose tag is "my-tag",
regardless of the node name.
doc.getAll(re.compile(r"-")) would return all nodes whose name starts with "-".
Etc.
ValueKey
Similarly to NodeKey, a few things take a ValueKey
to match against values,
based on its tag and/or type.
A ValueKey is either a TagKey or a (TagKey, TypeKey) tuple,
matching against the value's tag and/or type.
TagKey works identically to how it appears in NodeKey.
TypeKey is either ..., which matches any type,
or the same sort of argument you'd pass as the second argument to isinstance().
For example,
a "foo" key would match any values with the tag "foo", like (foo)1 or (foo)"bar".
A (..., kdl.Numberish) will match any value that's a "number" type: a Hex, Octal, Binary, Decimal, Infinity, or NaN, regardless of its tag.
Etc.
kdlreformat
The kdlreformat command-line program is installed by default
when you install this module from pypi.
It can also be run manually from the kdlreformat.py file
at the root of this repository
(or from the kdl.cli.cli() function).
Because it uses the default version="auto" parser and always prints KDL 2.0,
it can also be used to upgrade KDL 1.0 files to canonical KDL 2.0.
usage: kdlreformat [-h] [--indent INDENT] [--semicolons] [--radix]
[--no-radix] [--string-type {auto,exact,plain}]
[--raw-strings] [--no-raw-strings] [--exponent EXPONENT]
[--sort-properties] [--version {1,2,auto}]
[infile] [outfile]
KDL parser/printer, letting you easily reformat KDL files into a canonical
representation.
positional arguments:
infile
outfile
options:
-h, --help show this help message and exit
--indent INDENT How many spaces for each level of indent. -1 indicates
to indent with tabs.
--semicolons Whether to end nodes with semicolons or not.
--radix Output numeric values in the radix used by the input.
(0x1a outputs as 0x1a)
--no-radix Convert all numeric arguments to decimal. (0x1a
outputs as 26)
--string-type {auto,exact,plain}
How to format strings: 'auto' (preserve raw strings,
pick cleanest form otherwise; default), 'exact'
(preserve input ident/quoted/raw string types), or
'plain' (always output ident or quoted strings, never
raw).
--raw-strings Alias for --string-type=exact.
--no-raw-strings Alias for --string-type=plain.
--exponent EXPONENT What character to use ('e' or 'E') for indicating
exponents on scinot numbers.
--sort-properties Sort node properties lexicographically by key instead
of preserving insertion order.
--version {1,2,auto} KDL grammar version to parse ('1', '2', or 'auto').
(Printing is always KDL2.) Default is 'auto'.
Metadata
Release files for kdl-py 1.4.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| kdl_py-1.4.0.tar.gz | 76.9 kB | Without provenance | Details for kdl_py-1.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| kdl_py-1.4.0-py3-none-any.whl | Python 3 | none | any | Details for kdl_py-1.4.0-py3-none-any.whl |
Total release size: 130.2 kB
Release files / kdl_py-1.4.0.tar.gz
| Download URL | kdl_py-1.4.0.tar.gz |
|---|---|
| Size | 76.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
071f6e3fa35fb68a87107b08ec25c6db3e7a41f5b27e7c7138b4bc940c4b2e7c
|
|
BLAKE2b-256 checksum How to use checksums |
3cbaabfc1e1cacfe5565875c4a168c7205310b17bb6106a6960e7191a9b24ecb
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.6
|
Release files / kdl_py-1.4.0-py3-none-any.whl
| Download URL | kdl_py-1.4.0-py3-none-any.whl |
|---|---|
| Size | 53.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
51c66eb7245b0a0f9c0038e73ccfa3b162c1273bb10ec231b3671752ebb5a7b1
|
|
BLAKE2b-256 checksum How to use checksums |
f6999b25d8d9e2bafd7df6c66d3028ade20bc131fc8f84c2ebfe081e6e8911c5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.6
|
Security for kdl-py 1.4.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.