ryaml 0.6.0__cp315-cp315-android_24_arm64_v8a.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ryaml/__init__.py +91 -0
- ryaml/_ryaml.cpython-315-aarch64-linux-android.so +0 -0
- ryaml/_ryaml.pyi +44 -0
- ryaml/_scalars.py +50 -0
- ryaml/compat/__init__.py +106 -0
- ryaml/error.py +112 -0
- ryaml/py.typed +0 -0
- ryaml-0.6.0.dist-info/METADATA +235 -0
- ryaml-0.6.0.dist-info/RECORD +12 -0
- ryaml-0.6.0.dist-info/WHEEL +4 -0
- ryaml-0.6.0.dist-info/licenses/LICENSE +63 -0
- ryaml-0.6.0.dist-info/sboms/ryaml.cyclonedx.json +770 -0
ryaml/__init__.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
from ._ryaml import InvalidYamlError, loads, loads_all, dumps as _dumps
|
|
2
|
+
from .error import (
|
|
3
|
+
ScannerError,
|
|
4
|
+
ParserError,
|
|
5
|
+
ComposerError,
|
|
6
|
+
ConstructorError,
|
|
7
|
+
EmitterError,
|
|
8
|
+
SerializerError,
|
|
9
|
+
RepresenterError,
|
|
10
|
+
ReaderError,
|
|
11
|
+
)
|
|
12
|
+
from .compat import RSafeDumper, RSafeLoader, Representer
|
|
13
|
+
|
|
14
|
+
from typing import IO, AnyStr, Any
|
|
15
|
+
import io
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"InvalidYamlError",
|
|
19
|
+
"loads",
|
|
20
|
+
"loads_all",
|
|
21
|
+
"dumps",
|
|
22
|
+
"add_representer",
|
|
23
|
+
"add_multi_representer",
|
|
24
|
+
"ScannerError",
|
|
25
|
+
"ParserError",
|
|
26
|
+
"ComposerError",
|
|
27
|
+
"ConstructorError",
|
|
28
|
+
"EmitterError",
|
|
29
|
+
"SerializerError",
|
|
30
|
+
"RepresenterError",
|
|
31
|
+
"ReaderError",
|
|
32
|
+
"RSafeDumper",
|
|
33
|
+
"RSafeLoader",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _read_file(fp: IO[AnyStr]) -> str | bytes:
|
|
38
|
+
data = fp.read()
|
|
39
|
+
if isinstance(data, str):
|
|
40
|
+
return data
|
|
41
|
+
# Decoded in Rust: a UTF-16 BOM selects UTF-16, otherwise UTF-8.
|
|
42
|
+
return bytes(data)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def load(fp: IO[AnyStr]) -> Any:
|
|
46
|
+
if not isinstance(fp, io.IOBase):
|
|
47
|
+
raise TypeError("fp must be a file-like object")
|
|
48
|
+
return loads(_read_file(fp))
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def load_all(fp: IO[AnyStr]) -> list[Any]:
|
|
52
|
+
if not isinstance(fp, io.IOBase):
|
|
53
|
+
raise TypeError("fp must be a file-like object")
|
|
54
|
+
return loads_all(_read_file(fp))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def add_representer(
|
|
58
|
+
data_type: type | None, representer: Representer, Dumper: type[RSafeDumper] = RSafeDumper,
|
|
59
|
+
) -> None:
|
|
60
|
+
"""Register a representer for an exact type on the given dumper class."""
|
|
61
|
+
Dumper.add_representer(data_type, representer)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def add_multi_representer(
|
|
65
|
+
data_type: type | None, multi_representer: Representer,
|
|
66
|
+
Dumper: type[RSafeDumper] = RSafeDumper,
|
|
67
|
+
) -> None:
|
|
68
|
+
"""Register a representer for a type and its subclasses on the given dumper class."""
|
|
69
|
+
Dumper.add_multi_representer(data_type, multi_representer)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def dumps(obj: Any, *, Dumper: type[RSafeDumper] = RSafeDumper) -> str:
|
|
73
|
+
if Dumper is RSafeDumper and not Dumper._has_custom_representers():
|
|
74
|
+
return _dumps(obj)
|
|
75
|
+
stream = io.StringIO()
|
|
76
|
+
dumper = Dumper(stream, sort_keys=False)
|
|
77
|
+
try:
|
|
78
|
+
dumper.open()
|
|
79
|
+
dumper.represent(obj)
|
|
80
|
+
dumper.close()
|
|
81
|
+
finally:
|
|
82
|
+
dumper.dispose()
|
|
83
|
+
return stream.getvalue()
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def dump(fp: IO[AnyStr], obj: Any, *, Dumper: type[RSafeDumper] = RSafeDumper) -> None:
|
|
87
|
+
yaml = dumps(obj, Dumper=Dumper)
|
|
88
|
+
if isinstance(fp, io.TextIOBase):
|
|
89
|
+
fp.write(yaml) # type: ignore
|
|
90
|
+
else:
|
|
91
|
+
fp.write(yaml.encode("utf8")) # type: ignore
|
|
Binary file
|
ryaml/_ryaml.pyi
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# pyright: strict
|
|
2
|
+
from collections.abc import Mapping, MutableMapping
|
|
3
|
+
from typing import IO, Any
|
|
4
|
+
|
|
5
|
+
class InvalidYamlError(ValueError): ...
|
|
6
|
+
|
|
7
|
+
def loads(s: str | bytes) -> Any: ...
|
|
8
|
+
def loads_all(s: str | bytes) -> list[Any]: ...
|
|
9
|
+
def dumps(obj: Any) -> str: ...
|
|
10
|
+
|
|
11
|
+
class _RSafeLoader:
|
|
12
|
+
# Note that this class only takes str | bytes because we want to do all I/O
|
|
13
|
+
# at the Python layer
|
|
14
|
+
def __init__(self, stream: str | bytes) -> None: ...
|
|
15
|
+
|
|
16
|
+
class _RSafeDumper:
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
stream: IO[str] | IO[bytes],
|
|
20
|
+
default_style: str | None = None,
|
|
21
|
+
default_flow_style: bool | None = False,
|
|
22
|
+
canonical: bool | None = None,
|
|
23
|
+
indent: int | None = None,
|
|
24
|
+
width: int | None = None,
|
|
25
|
+
allow_unicode: bool | None = None,
|
|
26
|
+
line_break: str | None = None,
|
|
27
|
+
encoding: str | None = None,
|
|
28
|
+
explicit_start: bool | None = None,
|
|
29
|
+
explicit_end: bool | None = None,
|
|
30
|
+
version: tuple[int, int] | None = None,
|
|
31
|
+
tags: dict[str, str] | None = None,
|
|
32
|
+
sort_keys: bool = True,
|
|
33
|
+
) -> None: ...
|
|
34
|
+
alias_key: int | None
|
|
35
|
+
@property
|
|
36
|
+
def represented_objects(self) -> MutableMapping[int, Any]: ...
|
|
37
|
+
@represented_objects.setter
|
|
38
|
+
def represented_objects(self, objects: Mapping[int, Any]) -> None: ...
|
|
39
|
+
def open(self) -> None: ...
|
|
40
|
+
def represent(self, data: Any) -> None: ...
|
|
41
|
+
def represent_data(self, data: Any) -> Any: ...
|
|
42
|
+
def serialize(self, node: Any) -> None: ...
|
|
43
|
+
def close(self) -> None: ...
|
|
44
|
+
def dispose(self) -> None: ...
|
ryaml/_scalars.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Construct the scalar types which need Python's standard library."""
|
|
2
|
+
|
|
3
|
+
import binascii
|
|
4
|
+
import datetime
|
|
5
|
+
import re
|
|
6
|
+
|
|
7
|
+
from .error import ConstructorError
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
_TIMESTAMP = re.compile(
|
|
11
|
+
r"^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})"
|
|
12
|
+
r"(?:(?:[Tt]|[ \t]+)([0-9]{1,2}):([0-9]{2}):([0-9]{2})"
|
|
13
|
+
r"(?:\.([0-9]*))?"
|
|
14
|
+
r"(?:[ \t]*(Z|([-+])([0-9]{1,2})(?::([0-9]{2}))?))?)?$"
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def timestamp(value: str) -> datetime.date | datetime.datetime:
|
|
19
|
+
# Explicit tags use this pattern too, including single-digit months/days.
|
|
20
|
+
# Like PyYAML, which calls match.groupdict(), malformed explicitly tagged
|
|
21
|
+
# timestamps raise AttributeError; invalid calendar fields are rejected by
|
|
22
|
+
# datetime with ValueError.
|
|
23
|
+
match = _TIMESTAMP.match(value)
|
|
24
|
+
if match is None:
|
|
25
|
+
raise AttributeError("'NoneType' object has no attribute 'groupdict'")
|
|
26
|
+
year, month, day, hour, minute, second, fraction, zone, sign, zh, zm = match.groups()
|
|
27
|
+
date = (int(year), int(month), int(day))
|
|
28
|
+
if hour is None:
|
|
29
|
+
return datetime.date(*date)
|
|
30
|
+
tz = None
|
|
31
|
+
if sign:
|
|
32
|
+
offset = datetime.timedelta(hours=int(zh), minutes=int(zm or 0))
|
|
33
|
+
tz = datetime.timezone(-offset if sign == "-" else offset)
|
|
34
|
+
elif zone:
|
|
35
|
+
tz = datetime.timezone.utc
|
|
36
|
+
return datetime.datetime(
|
|
37
|
+
*date, int(hour), int(minute), int(second),
|
|
38
|
+
int((fraction or "")[:6].ljust(6, "0")), tzinfo=tz,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def binary(value: str) -> bytes:
|
|
43
|
+
try:
|
|
44
|
+
encoded = value.encode("ascii")
|
|
45
|
+
except UnicodeEncodeError as error:
|
|
46
|
+
raise ConstructorError(f"failed to convert base64 data into ascii: {error}") from error
|
|
47
|
+
try:
|
|
48
|
+
return binascii.a2b_base64(encoded)
|
|
49
|
+
except binascii.Error as error:
|
|
50
|
+
raise ConstructorError(f"failed to decode base64 data: {error}") from error
|
ryaml/compat/__init__.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""PyYAML-compatible loaders and dumpers backed by Rust."""
|
|
2
|
+
|
|
3
|
+
from types import MappingProxyType
|
|
4
|
+
from typing import TYPE_CHECKING, Any, Callable, Protocol, TypeAlias, TypeVar
|
|
5
|
+
|
|
6
|
+
from ryaml._ryaml import _RSafeLoader, _RSafeDumper
|
|
7
|
+
from ryaml.error import RepresenterError
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
from yaml import BaseLoader
|
|
11
|
+
from yaml.constructor import BaseConstructor
|
|
12
|
+
from yaml.representer import SafeRepresenter
|
|
13
|
+
from yaml.resolver import BaseResolver
|
|
14
|
+
except ModuleNotFoundError as exc:
|
|
15
|
+
if exc.name != "yaml":
|
|
16
|
+
raise
|
|
17
|
+
BaseLoader = object
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from yaml.nodes import Node
|
|
21
|
+
|
|
22
|
+
__all__ = ["RSafeLoader", "RSafeDumper"]
|
|
23
|
+
|
|
24
|
+
Representer: TypeAlias = Callable[["RSafeDumper", Any], "Node"]
|
|
25
|
+
|
|
26
|
+
# SupportsRead Protocol from the definition in typeshed
|
|
27
|
+
_T_co = TypeVar("_T_co", covariant=True)
|
|
28
|
+
|
|
29
|
+
class SupportsRead(Protocol[_T_co]):
|
|
30
|
+
def read(self, length: int = ..., /) -> _T_co: ...
|
|
31
|
+
|
|
32
|
+
# From the pyyaml type defintions in typeshed
|
|
33
|
+
Readable: TypeAlias = SupportsRead[str | bytes]
|
|
34
|
+
|
|
35
|
+
class RSafeLoader(_RSafeLoader, BaseLoader):
|
|
36
|
+
def __new__(cls, stream: str | bytes | Readable) -> "RSafeLoader":
|
|
37
|
+
try:
|
|
38
|
+
data = stream.read() # type: ignore
|
|
39
|
+
except AttributeError:
|
|
40
|
+
data = stream
|
|
41
|
+
return super().__new__(cls, data) # type: ignore
|
|
42
|
+
|
|
43
|
+
def __init__(self, stream: str | bytes | Readable) -> None:
|
|
44
|
+
# The Rust loader reads and decodes the stream itself. BaseLoader's
|
|
45
|
+
# Reader/Scanner would read it again in Python and raise PyYAML's own
|
|
46
|
+
# errors first (eagerly, for invalid bytes or characters), so only set
|
|
47
|
+
# up the parts of BaseLoader that hold no input.
|
|
48
|
+
self.stream = stream
|
|
49
|
+
self.name = getattr(stream, "name", "<file>")
|
|
50
|
+
if BaseLoader is not object:
|
|
51
|
+
BaseConstructor.__init__(self)
|
|
52
|
+
BaseResolver.__init__(self)
|
|
53
|
+
|
|
54
|
+
if BaseLoader is object:
|
|
55
|
+
class _SafeRepresenter:
|
|
56
|
+
yaml_representers = MappingProxyType({})
|
|
57
|
+
yaml_multi_representers = MappingProxyType({})
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def add_representer(cls, data_type: type | None, representer: Representer) -> None:
|
|
61
|
+
raise ModuleNotFoundError("Custom representers require PyYAML", name="yaml")
|
|
62
|
+
|
|
63
|
+
add_multi_representer = add_representer
|
|
64
|
+
else:
|
|
65
|
+
def _represent_undefined(dumper: "RSafeDumper", data: Any) -> "Node":
|
|
66
|
+
raise RepresenterError(f"cannot represent an object: {data!r}")
|
|
67
|
+
|
|
68
|
+
class _SafeRepresenter(SafeRepresenter):
|
|
69
|
+
# PyYAML copies each registry when a subclass first registers a callback.
|
|
70
|
+
# Keep the defaults independent of PyYAML's own registration API.
|
|
71
|
+
yaml_representers = MappingProxyType({
|
|
72
|
+
**SafeRepresenter.yaml_representers,
|
|
73
|
+
None: _represent_undefined,
|
|
74
|
+
})
|
|
75
|
+
yaml_multi_representers = MappingProxyType(SafeRepresenter.yaml_multi_representers.copy())
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class RSafeDumper(_RSafeDumper, _SafeRepresenter):
|
|
79
|
+
"""PyYAML-compatible safe YAML dumper backed by Rust.
|
|
80
|
+
|
|
81
|
+
The built-in types SafeRepresenter handles are represented in Rust unless
|
|
82
|
+
a representer registered on the class replaces SafeRepresenter's. Other
|
|
83
|
+
types are looked up like PyYAML: the exact type in ``yaml_representers``,
|
|
84
|
+
then the type's MRO in ``yaml_multi_representers``, then ``None`` in each.
|
|
85
|
+
Representers get this dumper, whose ``represent_data``, ``alias_key`` and
|
|
86
|
+
``represented_objects`` are backed by Rust, so PyYAML's own
|
|
87
|
+
``represent_scalar``, ``represent_sequence`` and ``represent_mapping``
|
|
88
|
+
work with it.
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
def __init__(
|
|
92
|
+
self, stream, default_style=None, default_flow_style=False, canonical=None,
|
|
93
|
+
indent=None, width=None, allow_unicode=None, line_break=None, encoding=None,
|
|
94
|
+
explicit_start=None, explicit_end=None, version=None, tags=None, sort_keys=True,
|
|
95
|
+
) -> None:
|
|
96
|
+
# The options PyYAML's representer methods read, as given.
|
|
97
|
+
self.default_style = default_style
|
|
98
|
+
self.default_flow_style = default_flow_style
|
|
99
|
+
self.sort_keys = sort_keys
|
|
100
|
+
|
|
101
|
+
@classmethod
|
|
102
|
+
def _has_custom_representers(cls) -> bool:
|
|
103
|
+
return (
|
|
104
|
+
cls.yaml_representers is not _SafeRepresenter.yaml_representers
|
|
105
|
+
or cls.yaml_multi_representers is not _SafeRepresenter.yaml_multi_representers
|
|
106
|
+
)
|
ryaml/error.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Exception classes for ryaml, compatible with both older ryaml and pyyaml.
|
|
2
|
+
|
|
3
|
+
All exceptions subclass InvalidYamlError for backwards compatibility.
|
|
4
|
+
When pyyaml is installed, they also subclass the corresponding pyyaml
|
|
5
|
+
exception so that ``except yaml.ScannerError`` (etc.) catches ryaml errors.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from ._ryaml import InvalidYamlError
|
|
9
|
+
|
|
10
|
+
try:
|
|
11
|
+
from yaml.error import YAMLError as _YAMLError, MarkedYAMLError as _MarkedYAMLError
|
|
12
|
+
from yaml.scanner import ScannerError as _PyScannerError
|
|
13
|
+
from yaml.parser import ParserError as _PyParserError
|
|
14
|
+
from yaml.composer import ComposerError as _PyComposerError
|
|
15
|
+
from yaml.constructor import ConstructorError as _PyConstructorError
|
|
16
|
+
from yaml.emitter import EmitterError as _PyEmitterError
|
|
17
|
+
from yaml.serializer import SerializerError as _PySerializerError
|
|
18
|
+
from yaml.representer import RepresenterError as _PyRepresenterError
|
|
19
|
+
from yaml.reader import ReaderError as _PyReaderError
|
|
20
|
+
_HAS_YAML = True
|
|
21
|
+
except ImportError:
|
|
22
|
+
_HAS_YAML = False
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _MarkedErrorMixin:
|
|
26
|
+
"""Provide MarkedYAMLError-compatible attributes for exceptions raised with a plain string."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, context=None, context_mark=None,
|
|
29
|
+
problem=None, problem_mark=None, note=None):
|
|
30
|
+
# When raised from Rust with a single positional string, map it to `problem`.
|
|
31
|
+
if isinstance(context, str) and context_mark is None and problem is None:
|
|
32
|
+
problem = context
|
|
33
|
+
context = None
|
|
34
|
+
self.context = context
|
|
35
|
+
self.context_mark = context_mark
|
|
36
|
+
self.problem = problem
|
|
37
|
+
self.problem_mark = problem_mark
|
|
38
|
+
self.note = note
|
|
39
|
+
parts = []
|
|
40
|
+
if context is not None:
|
|
41
|
+
parts.append(str(context))
|
|
42
|
+
if problem is not None:
|
|
43
|
+
parts.append(str(problem))
|
|
44
|
+
super().__init__("\n".join(parts) if parts else "")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
if _HAS_YAML:
|
|
48
|
+
class ScannerError(_MarkedErrorMixin, InvalidYamlError, _PyScannerError):
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
class ParserError(_MarkedErrorMixin, InvalidYamlError, _PyParserError):
|
|
52
|
+
pass
|
|
53
|
+
|
|
54
|
+
class ComposerError(_MarkedErrorMixin, InvalidYamlError, _PyComposerError):
|
|
55
|
+
pass
|
|
56
|
+
|
|
57
|
+
class ConstructorError(_MarkedErrorMixin, InvalidYamlError, _PyConstructorError):
|
|
58
|
+
pass
|
|
59
|
+
|
|
60
|
+
class EmitterError(InvalidYamlError, _PyEmitterError):
|
|
61
|
+
pass
|
|
62
|
+
|
|
63
|
+
class SerializerError(InvalidYamlError, _PySerializerError):
|
|
64
|
+
pass
|
|
65
|
+
|
|
66
|
+
class RepresenterError(InvalidYamlError, _PyRepresenterError):
|
|
67
|
+
pass
|
|
68
|
+
|
|
69
|
+
class ReaderError(InvalidYamlError, _PyReaderError):
|
|
70
|
+
def __init__(self, *args, **kwargs):
|
|
71
|
+
# Accept either a plain string (from Rust) or the pyyaml 5-arg form.
|
|
72
|
+
if len(args) == 1 and isinstance(args[0], str) and not kwargs:
|
|
73
|
+
InvalidYamlError.__init__(self, args[0])
|
|
74
|
+
self.name = None
|
|
75
|
+
self.position = None
|
|
76
|
+
self.character = None
|
|
77
|
+
self.encoding = None
|
|
78
|
+
self.reason = args[0]
|
|
79
|
+
else:
|
|
80
|
+
_PyReaderError.__init__(self, *args, **kwargs)
|
|
81
|
+
|
|
82
|
+
def __str__(self):
|
|
83
|
+
# PyYAML's __str__ formats the 5-arg form; a message from Rust has
|
|
84
|
+
# no character/position to format.
|
|
85
|
+
if self.character is None:
|
|
86
|
+
return str(self.reason)
|
|
87
|
+
return _PyReaderError.__str__(self)
|
|
88
|
+
|
|
89
|
+
else:
|
|
90
|
+
class ScannerError(_MarkedErrorMixin, InvalidYamlError):
|
|
91
|
+
pass
|
|
92
|
+
|
|
93
|
+
class ParserError(_MarkedErrorMixin, InvalidYamlError):
|
|
94
|
+
pass
|
|
95
|
+
|
|
96
|
+
class ComposerError(_MarkedErrorMixin, InvalidYamlError):
|
|
97
|
+
pass
|
|
98
|
+
|
|
99
|
+
class ConstructorError(_MarkedErrorMixin, InvalidYamlError):
|
|
100
|
+
pass
|
|
101
|
+
|
|
102
|
+
class EmitterError(InvalidYamlError):
|
|
103
|
+
pass
|
|
104
|
+
|
|
105
|
+
class SerializerError(InvalidYamlError):
|
|
106
|
+
pass
|
|
107
|
+
|
|
108
|
+
class RepresenterError(InvalidYamlError):
|
|
109
|
+
pass
|
|
110
|
+
|
|
111
|
+
class ReaderError(InvalidYamlError):
|
|
112
|
+
pass
|
ryaml/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ryaml
|
|
3
|
+
Version: 0.6.0
|
|
4
|
+
Classifier: Programming Language :: Python
|
|
5
|
+
Classifier: Programming Language :: Rust
|
|
6
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
7
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Environment :: WebAssembly :: Emscripten
|
|
13
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
14
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
15
|
+
Classifier: Operating System :: MacOS
|
|
16
|
+
Classifier: Operating System :: Android
|
|
17
|
+
Classifier: Operating System :: iOS
|
|
18
|
+
Classifier: Typing :: Typed
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Summary: A pyyaml compatible YAML 1.1 parser in Rust.
|
|
21
|
+
Keywords: yaml,parsing
|
|
22
|
+
Author-email: Emma Harper Smith <emma@emmatyping.dev>
|
|
23
|
+
License: MIT
|
|
24
|
+
Requires-Python: >=3.11, <4
|
|
25
|
+
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
|
|
26
|
+
Project-URL: homepage, https://github.com/emmatyping/ryaml
|
|
27
|
+
Project-URL: repository, https://github.com/emmatyping/ryaml
|
|
28
|
+
|
|
29
|
+
ryaml
|
|
30
|
+
=====
|
|
31
|
+
|
|
32
|
+
### *Quickly and safely parse yaml*
|
|
33
|
+
|
|
34
|
+
### What is ryaml?
|
|
35
|
+
|
|
36
|
+
ryaml is a Python library that wraps a Rust yaml parser, [libyaml-safer](https://github.com/simonask/libyaml-safer),
|
|
37
|
+
to quickly and safely parse and dump yaml to and from Python objects.
|
|
38
|
+
|
|
39
|
+
The project is *drop-in compatible* with PyYAML's `CSafeLoader` and `CSafeDumper`, meaning that any behavior differences are a bug and should be reported against this project.
|
|
40
|
+
|
|
41
|
+
Like PyYAML, this library implements the YAML 1.1 specification.
|
|
42
|
+
|
|
43
|
+
## Installation
|
|
44
|
+
|
|
45
|
+
We ship binary wheels for Linux (manylinux and musllinux), Windows, macOS, Android, iOS,
|
|
46
|
+
and Pyodide (WebAssembly), including free-threaded CPython builds, so as long as you are
|
|
47
|
+
using Python 3.11+, you can run:
|
|
48
|
+
|
|
49
|
+
```
|
|
50
|
+
$ python -m pip install ryaml
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Otherwise, you will need to build from source. To do so, first install Rust 1.89 or newer.
|
|
54
|
+
|
|
55
|
+
Then you should be able to just
|
|
56
|
+
|
|
57
|
+
```shell
|
|
58
|
+
$ git clone https://github.com/emmatyping/ryaml
|
|
59
|
+
$ cd ryaml
|
|
60
|
+
$ python -m pip install .
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Or if you want to build a wheel:
|
|
64
|
+
|
|
65
|
+
```shell
|
|
66
|
+
$ git clone https://github.com/emmatyping/ryaml
|
|
67
|
+
$ cd ryaml
|
|
68
|
+
$ python -m pip install maturin
|
|
69
|
+
$ maturin build --release
|
|
70
|
+
# OR if you want an abi3 wheel (compatible with Python 3.11+, except free-threaded builds)
|
|
71
|
+
$ maturin build --release --features abi3
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
And a wheel will be created in `target/wheels` which you can install.
|
|
75
|
+
|
|
76
|
+
## Usage
|
|
77
|
+
|
|
78
|
+
The API of `ryaml` is very similar to that of `json` in the standard library:
|
|
79
|
+
|
|
80
|
+
You can use `ryaml.loads` to read from a `str` (or UTF-8/UTF-16 `bytes`):
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
import ryaml
|
|
84
|
+
obj = ryaml.loads('key: [10, "hi"]')
|
|
85
|
+
assert isinstance(obj, dict) # True
|
|
86
|
+
assert obj['key'][1] == "hi" # True
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
And `ryaml.dumps` to dump an object into a yaml file:
|
|
90
|
+
|
|
91
|
+
```python
|
|
92
|
+
import ryaml
|
|
93
|
+
s = ryaml.dumps({ 'key' : None })
|
|
94
|
+
print(s)
|
|
95
|
+
# prints:
|
|
96
|
+
# key: null
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
There are also `ryaml.load` and `ryaml.load_all` to read yaml document(s) from files:
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
import ryaml
|
|
103
|
+
obj = {'a': [{'b': 1}]}
|
|
104
|
+
with open('test.yaml', 'w') as w:
|
|
105
|
+
ryaml.dump(w, obj)
|
|
106
|
+
with open('test.yaml', 'r') as r:
|
|
107
|
+
assert ryaml.load(r) == obj
|
|
108
|
+
with open('multidoc.yaml', 'w') as multi:
|
|
109
|
+
multi.write('''
|
|
110
|
+
---
|
|
111
|
+
a:
|
|
112
|
+
key:
|
|
113
|
+
...
|
|
114
|
+
---
|
|
115
|
+
b:
|
|
116
|
+
key:
|
|
117
|
+
''')
|
|
118
|
+
with open('multidoc.yaml', 'r') as multi:
|
|
119
|
+
docs = ryaml.load_all(multi)
|
|
120
|
+
assert len(docs) == 2
|
|
121
|
+
assert docs[0]['a']['key'] is None
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
`ryaml.load_all` will, as seen above, load multiple documents from a single file, and `ryaml.loads_all`
|
|
125
|
+
does the same for a `str`.
|
|
126
|
+
|
|
127
|
+
### Using ryaml with PyYAML
|
|
128
|
+
|
|
129
|
+
If you already use PyYAML, pass `ryaml.RSafeLoader` or `ryaml.RSafeDumper` in place of `CSafeLoader`
|
|
130
|
+
or `CSafeDumper`:
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
import yaml
|
|
134
|
+
import ryaml
|
|
135
|
+
obj = yaml.load('key: [10, "hi"]', Loader=ryaml.RSafeLoader)
|
|
136
|
+
print(yaml.dump(obj, Dumper=ryaml.RSafeDumper))
|
|
137
|
+
# prints:
|
|
138
|
+
# key:
|
|
139
|
+
# - 10
|
|
140
|
+
# - hi
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### Custom representers
|
|
144
|
+
|
|
145
|
+
With PyYAML installed, register callbacks on `ryaml.RSafeDumper` or on a subclass
|
|
146
|
+
to control how Python objects become YAML nodes. `add_representer` matches an
|
|
147
|
+
exact type. `add_multi_representer` matches a type and its subclasses using
|
|
148
|
+
Python's method resolution order. An exact registration takes precedence.
|
|
149
|
+
|
|
150
|
+
```python
|
|
151
|
+
from datetime import timedelta
|
|
152
|
+
from pathlib import PurePath
|
|
153
|
+
|
|
154
|
+
import ryaml
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class ConfigDumper(ryaml.RSafeDumper):
|
|
158
|
+
pass
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def represent_path(dumper, path):
|
|
162
|
+
return dumper.represent_scalar("tag:yaml.org,2002:str", path.as_posix())
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def represent_duration(dumper, duration):
|
|
166
|
+
return dumper.represent_scalar("tag:yaml.org,2002:int", str(int(duration.total_seconds())))
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
ConfigDumper.add_multi_representer(PurePath, represent_path)
|
|
170
|
+
ConfigDumper.add_representer(timedelta, represent_duration)
|
|
171
|
+
|
|
172
|
+
config = {"path": PurePath("config.yaml"), "timeout": timedelta(minutes=25)}
|
|
173
|
+
print(ryaml.dumps(config, Dumper=ConfigDumper))
|
|
174
|
+
# prints:
|
|
175
|
+
# path: config.yaml
|
|
176
|
+
# timeout: 1500
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
Pass the same class as `Dumper=` to `ryaml.dump` or `yaml.dump`. The module-level
|
|
180
|
+
`ryaml.add_representer` and `ryaml.add_multi_representer` functions default to
|
|
181
|
+
registering on `ryaml.RSafeDumper`.
|
|
182
|
+
|
|
183
|
+
Representers work as in PyYAML: they can call `dumper.represent_scalar`,
|
|
184
|
+
`represent_sequence`, `represent_mapping` and `represent_data`, change the nodes
|
|
185
|
+
these return, or build `yaml.nodes` objects themselves. Registering a representer
|
|
186
|
+
for a built-in type such as `str` or `dict` replaces ryaml's. Built-in types without
|
|
187
|
+
one are still represented in Rust, so registering representers does not slow down
|
|
188
|
+
dumping the rest of the data.
|
|
189
|
+
|
|
190
|
+
The nodes a representer returns are written as PyYAML's `CSafeDumper` writes them,
|
|
191
|
+
with three differences: ryaml raises `TypeError` for anything that is not a node,
|
|
192
|
+
which `CSafeDumper` silently leaves out of sequences and otherwise rejects with
|
|
193
|
+
`EmitterError`; it writes subclasses of the node classes, as PyYAML's pure-Python
|
|
194
|
+
`SafeDumper` does, where `CSafeDumper` treats them as non-nodes; and for a `bytes`
|
|
195
|
+
tag or value that is not UTF-8 it raises `UnicodeDecodeError`, where `CSafeDumper`
|
|
196
|
+
raises `MemoryError`.
|
|
197
|
+
|
|
198
|
+
## Performance
|
|
199
|
+
|
|
200
|
+
ryaml is faster than PyYAML's `CSafeLoader` and `CSafeDumper` on all the files in our
|
|
201
|
+
[benchmarks](https://github.com/emmatyping/ryaml/tree/main/benchmark), which also has instructions for running them yourself.
|
|
202
|
+
|
|
203
|
+
## Development
|
|
204
|
+
|
|
205
|
+
Tests are run with [Hatch](https://hatch.pypa.io/), which installs from the hash-pinned
|
|
206
|
+
lockfiles in `locks/`:
|
|
207
|
+
|
|
208
|
+
```shell
|
|
209
|
+
$ hatch test # current Python
|
|
210
|
+
$ hatch test --python 3.14t # a specific Python, e.g. free-threaded 3.14
|
|
211
|
+
$ hatch run lint:run # pre-commit: rustfmt, clippy, zizmor and others
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
## Thanks
|
|
215
|
+
|
|
216
|
+
This project is standing on the shoulders of giants, and would not be possible without:
|
|
217
|
+
|
|
218
|
+
[pyo3](https://pyo3.rs/)
|
|
219
|
+
|
|
220
|
+
[libyaml-safer](https://github.com/simonask/libyaml-safer)
|
|
221
|
+
|
|
222
|
+
[saphyr-parser-bw](https://github.com/bourumir-wyngs/saphyr/tree/dev/saphyr-parser)
|
|
223
|
+
|
|
224
|
+
[pyyaml](https://github.com/yaml/pyyaml/)
|
|
225
|
+
|
|
226
|
+
[yaml-test-suite](https://github.com/yaml/yaml-test-suite)
|
|
227
|
+
|
|
228
|
+
Earlier versions of this library were based on the following projects:
|
|
229
|
+
|
|
230
|
+
[serde-yaml](https://github.com/dtolnay/serde-yaml)
|
|
231
|
+
|
|
232
|
+
[yaml-rust](https://github.com/chyh1990/yaml-rust)
|
|
233
|
+
|
|
234
|
+
[pythonize](https://github.com/davidhewitt/pythonize)
|
|
235
|
+
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
ryaml/__init__.py,sha256=Sp2Qi2qvUMEzC_LX_f-6lRWilMDp7prKBsVgJdPCjzw,2467
|
|
2
|
+
ryaml/_ryaml.cpython-315-aarch64-linux-android.so,sha256=Ev3cJMeS5lV-dQB6BdFY6e4E5IZOg5hqXD1TkIE3wLM,5746984
|
|
3
|
+
ryaml/_ryaml.pyi,sha256=jkvz4r74hL84BnOE3KAXYQmjiBj_9d40rY7OX8n_ins,1540
|
|
4
|
+
ryaml/_scalars.py,sha256=zOZIK_r08nv4kV3Id6mT1voA01GCZR61Wvg3VGPFJMg,1788
|
|
5
|
+
ryaml/error.py,sha256=IOXEsMXeL34RzrKBWwx0qATdwzV6lvh2QE8j40-KN1k,3896
|
|
6
|
+
ryaml/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
ryaml/compat/__init__.py,sha256=xKJmQ1uMKsZ5yVU9HnUFhllvLaaWvBbaZq5YrIM7yLY,4266
|
|
8
|
+
ryaml-0.6.0.dist-info/METADATA,sha256=1g63rBgdz-gmCN5TQfGp34y3gc6a7UQXI3STJNC8Xcc,7227
|
|
9
|
+
ryaml-0.6.0.dist-info/WHEEL,sha256=yRZtc7thNAwQqvAWWjXKxCPSwKqy10q_mWoyKuKYRW8,108
|
|
10
|
+
ryaml-0.6.0.dist-info/RECORD,,
|
|
11
|
+
ryaml-0.6.0.dist-info/licenses/LICENSE,sha256=9gEkh6m7yioYun_j6llQtQXinFsG3a18DH4r-qKRgxU,3573
|
|
12
|
+
ryaml-0.6.0.dist-info/sboms/ryaml.cyclonedx.json,sha256=A3qNpQRBEbte3KppOnz0F2bpY7ojZ03c7Nnx2mrAvk8,24644
|