Skip to content

Latest commit

 

History

History
123 lines (99 loc) · 6.23 KB

python-api.md

File metadata and controls

123 lines (99 loc) · 6.23 KB

Python API

The ylspec package requires CPython 3.11 or newer and uses its bundled native extension. Runtime installation has no Python package dependencies. The initial wheel targets are listed in compatibility.

Package identity

Created by Cavanşir Qurbanzadə and maintained under YoungLionOrganization. The public contact is [email protected]; original material is Apache-2.0. The Python package overview is also the PyPI description. Distribution metadata stores readable UTF-8 author/maintainer names separately from their ASCII email fields, avoiding registry-visible RFC 2047 display names. It includes maintainer identity, SPDX licensing, original/third-party notices, and canonical support and source links. Release assembly verifies these fields in every wheel and source distribution.

import ylspec
from importlib.metadata import metadata

assert ylspec.__author__ == "Cavanşir Qurbanzadə"
assert ylspec.__license__ == "Apache-2.0"
assert metadata("ylspec")["Version"] == ylspec.__version__

__maintainer__, __email__, __copyright__, and __url__ provide the matching runtime identity. Detailed attribution remains in AUTHORS.md.

Limits require integer values, excluding booleans. Explicit frame offsets and region lengths likewise require integers within the unsigned 64-bit range; oversized values raise OverflowError before native conversion or stream access. Negative offsets raise ValueError; a negative explicit region raises FrameError. Both dumps and pack require a Document and reject other values with TypeError.

Editor support and bundled type stubs

The package includes detailed PEP 561 type information alongside the native extension. No separate types-ylspec dependency or downloaded stub package is needed. Editors can provide completion and parameter documentation before the native module is imported.

Installed file Contract
ylspec/__init__.pyi Public API, recursive application values, envelope shapes, stream protocol, documented errors and limits
ylspec/_native.pyi Positional-only extension methods, normalized value transport, temporal tuples, callback and consumed-length contracts
ylspec/py.typed Marker identifying the distribution as a typed package

The public stub distinguishes application values from the reserved metadata table, preserves the return type of subclasses through Document.validate, accepts path-like objects where the runtime does, and requires a seekable binary reader for embedded I/O. Type checks cannot establish runtime size bounds, TOML syntax, profile approval, or the absence of cycles; those checks remain in the implementation.

GitHub Actions checks consumer examples with mypy and Pyright, compares the public stub against the installed implementation with stubtest, and verifies that every tested wheel includes both stubs and the marker. The same source files are included in the source distribution for downstream rebuilds.

Documents and values

Document(data=None, profile="core.data", profile_version="0.1", extensions=None, limits=Limits()) constructs the standard envelope around a data mapping. document.data, document.metadata, and document.extensions are mutable dictionaries. document.root contains the complete document. document.to_dict() returns a detached deep copy of that root.

Python value TOML meaning
str UTF-8 string
bool Boolean
int Signed 64-bit integer; overflow raises OverflowError
float Binary64, including infinities and NaN
Mapping with string keys Table
list or tuple Array
TemporalValue(kind, text) Exact validated temporal literal
datetime.date, datetime.time, datetime.datetime Serialized ISO temporal value
None, bytes as a value, arbitrary objects Unsupported; raises TypeError

Timezone-aware local time is unsupported because TOML has no offset-time type. Timezone-aware datetime becomes an offset datetime. Exact parsed temporal values remain TemporalValue; they do not silently lose precision through a conversion to Python's microsecond-limited datetime objects.

Functions

Function Result and behavior
loads(text, *, limits=Limits()) Parse str or bytes into Document
dumps(document) Revalidate and serialize to str
load(path, *, limits=Limits()) Read bounded binary text from a path
dump(document, path) Write serialized UTF-8 text; replaces that file
pack(document) Return a complete frame as bytes
unpack(buffer, offset=0, *, limits=Limits()) Read one frame from bytes; trailing host bytes are allowed
read_at(file, offset=0, *, available=None, limits=Limits()) Read one frame from a seekable binary file

read_at uses the C frame decoder through a Python read callback. It restores the file's original position. If available is omitted, it uses the file's size minus the supplied offset. A truncated underlying read raises OSError. Negative offsets are invalid. Text streams are not supported.

Serialization follows the document's limits. Cycles and unsupported values fail; they are never stringified implicitly. Comments and whitespace are not retained. See the executable example.

Validation and errors

document.validate(validators=None, *, features=()) first checks structure through the C core, then checks required capabilities and the selected profile. Validator keys are (profile, profile_version) tuples. A validator receives the document; returning False rejects it, while any other return accepts it. Raised exceptions propagate. The method returns the document on success.

All structured document errors inherit from ylspec.Error, which inherits ValueError. Specialized classes are ParseError, LimitError, FrameError, UnsupportedError, and ProfileError. Their attributes are code, offset, line, and column. C allocation failures are reported with code memory; Python-side allocations can raise MemoryError. Filesystem errors remain standard OSError subclasses.

Parsing an unknown profile is allowed for inspection; validating it without a registered handler fails explicitly. See profiles.