The lodum.yaml module provides YAML serialization and deserialization for lodum-enabled classes with support for multi-document streams.
Installation
Requires ruamel.yaml. Install with:
Functions
dump
def dump(
obj: Any,
target: Optional[Union[IO[str], Path]] = None,
**kwargs
) -> Optional[str]
Encodes a Python object to YAML.
target
Optional[Union[IO[str], Path]]
Optional file-like object or Path to write to.
Additional arguments for yaml.dump.
Returns: The YAML string if target is None, otherwise None.
Raises: ImportError if ruamel.yaml is not installed.
Example:
import lodum
from lodum import yaml
@lodum
class Person:
name: str
age: int
person = Person(name="Alice", age=30)
# Serialize to string
yaml_str = yaml.dump(person)
# Serialize to file
yaml.dump(person, Path("person.yaml"))
dumps
def dumps(obj: Any, **kwargs) -> str
Legacy alias for dump(obj).
Additional arguments for yaml.dump.
Returns: The YAML string.
load
def load(
cls: Type[T],
source: Union[str, IO[Any], Path],
max_size: int = DEFAULT_MAX_SIZE
) -> T
Decodes YAML from a string, stream, or file into a Python object.
The class to instantiate.
source
Union[str, IO[Any], Path]
required
YAML string, file-like object, or Path.
max_size
int
default:"DEFAULT_MAX_SIZE"
Maximum allowed size for string input.
Returns: An instance of cls.
Raises:
ImportError if ruamel.yaml is not installed.
DeserializationError if the input is invalid or exceeds max_size.
Example:
import lodum
from lodum import yaml
@lodum
class Person:
name: str
age: int
# Load from string
yaml_str = "name: Alice\nage: 30"
person = yaml.load(Person, yaml_str)
# Load from file
person = yaml.load(Person, Path("person.yaml"))
loads
def loads(cls: Type[T], yaml_string: str, **kwargs) -> T
Legacy alias for load(cls, source).
The class to instantiate.
Additional arguments (e.g., max_size).
Returns: An instance of cls.
stream
def stream(cls: Type[T], source: Union[IO[Any], Path]) -> Iterator[T]
Lazily decodes a stream of YAML documents.
The class to instantiate for each item.
source
Union[IO[Any], Path]
required
A stream, file-like object, or Path.
Returns: An iterator yielding instances of cls.
Raises: ImportError if ruamel.yaml is not installed.
Example:
import lodum
from lodum import yaml
@lodum
class Person:
name: str
age: int
# Stream from multi-document YAML file
for person in yaml.stream(Person, Path("people.yaml")):
print(person.name, person.age)
schema
def schema(cls: Type[Any]) -> Dict[str, Any]
Generates a JSON Schema for a given lodum-enabled class.
Returns: A dictionary representing the JSON Schema.
Example:
import lodum
from lodum import yaml
@lodum
class Person:
name: str
age: int
schema_dict = yaml.schema(Person)
print(schema_dict)