The lodum.toml module provides TOML serialization and deserialization for lodum-enabled classes.
Installation
Requires tomli (for reading) and tomli-w (for writing). Install with:
Note: Python 3.11+ includes tomllib in the standard library for reading TOML files.
Functions
dump
def dump(
obj: Any,
target: Optional[Union[IO[str], Path]] = None,
**kwargs
) -> Optional[str]
Encodes a Python object to TOML.
target
Optional[Union[IO[str], Path]]
Optional file-like object or Path to write to.
Additional arguments for tomli_w.dump(s).
Returns: The TOML string if target is None, otherwise None.
Raises: ImportError if tomli-w is not installed.
Example:
import lodum
from lodum import toml
@lodum
class Person:
name: str
age: int
person = Person(name="Alice", age=30)
# Serialize to string
toml_str = toml.dump(person)
# Serialize to file
toml.dump(person, Path("person.toml"))
dumps
def dumps(obj: Any, **kwargs) -> str
Legacy alias for dump(obj).
Additional arguments for tomli_w.dumps.
Returns: The TOML string.
load
def load(
cls: Type[T],
source: Union[str, IO[Any], Path],
max_size: int = DEFAULT_MAX_SIZE
) -> T
Decodes TOML from a string, stream, or file into a Python object.
The class to instantiate.
source
Union[str, IO[Any], Path]
required
TOML string, file-like object, or Path.
max_size
int
default:"DEFAULT_MAX_SIZE"
Maximum allowed size for string input.
Returns: An instance of cls populated with the decoded data.
Raises:
ImportError if tomllib (or tomli) is not installed.
DeserializationError if the input is invalid or exceeds max_size.
Example:
import lodum
from lodum import toml
@lodum
class Person:
name: str
age: int
# Load from string
toml_str = 'name = "Alice"\nage = 30'
person = toml.load(Person, toml_str)
# Load from file
person = toml.load(Person, Path("person.toml"))
loads
def loads(cls: Type[T], toml_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.
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 toml
@lodum
class Person:
name: str
age: int
schema_dict = toml.schema(Person)
print(schema_dict)
Notes
- TOML has limitations compared to other formats (e.g., no top-level arrays before TOML 1.1)
- Bytes are encoded as base64 strings for compatibility