The lodum.cbor module provides CBOR (Concise Binary Object Representation) serialization and deserialization for lodum-enabled classes with support for streaming.
Installation
Requires cbor2. Install with:
Functions
dump
def dump(
obj: Any,
target: Optional[Union[IO[bytes], Path]] = None,
**kwargs
) -> Optional[bytes]
Encodes a Python object to CBOR.
target
Optional[Union[IO[bytes], Path]]
Optional file-like object or Path to write to.
Additional arguments for cbor2.dump(s).
Returns: The CBOR bytes if target is None, otherwise None.
Raises: ImportError if cbor2 is not installed.
Example:
import lodum
from lodum import cbor
@lodum
class Person:
name: str
age: int
person = Person(name="Alice", age=30)
# Serialize to bytes
cbor_bytes = cbor.dump(person)
# Serialize to file
cbor.dump(person, Path("person.cbor"))
dumps
def dumps(obj: Any, **kwargs) -> bytes
Legacy alias for dump(obj).
Additional arguments for cbor2.dumps.
Returns: The CBOR bytes.
load
def load(
cls: Type[T],
source: Union[bytes, IO[bytes], Path],
max_size: int = DEFAULT_MAX_SIZE
) -> T
Decodes CBOR from bytes, stream, or file into a Python object.
The class to instantiate.
source
Union[bytes, IO[bytes], Path]
required
CBOR bytes, file-like object, or Path.
max_size
int
default:"DEFAULT_MAX_SIZE"
Maximum allowed size for bytes input.
Returns: An instance of cls.
Raises:
ImportError if cbor2 is not installed.
DeserializationError if the input is invalid or exceeds max_size.
Example:
import lodum
from lodum import cbor
@lodum
class Person:
name: str
age: int
# Load from bytes
cbor_bytes = b'\xa2dname\x65Alice\x63age\x18\x1e'
person = cbor.load(Person, cbor_bytes)
# Load from file
person = cbor.load(Person, Path("person.cbor"))
loads
def loads(cls: Type[T], cbor_bytes: bytes, **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[bytes], Path]) -> Iterator[T]
Lazily decodes a stream of CBOR objects. Supports concatenated CBOR objects.
The class to instantiate for each item.
source
Union[IO[bytes], Path]
required
A binary stream, file-like object, or Path.
Returns: An iterator yielding instances of cls.
Raises:
ImportError if cbor2 is not installed.
DeserializationError if the source type is unsupported for streaming.
Example:
import lodum
from lodum import cbor
@lodum
class Person:
name: str
age: int
# Stream from file containing concatenated CBOR objects
for person in cbor.stream(Person, Path("people.cbor")):
print(person.name, person.age)
Notes
- CBOR is a binary format defined in RFC 8949
- It’s more compact than JSON and supports additional data types
- Native bytes support without base64 encoding
- The
CBORDecoder is used for streaming to handle concatenated CBOR objects