CBOR (Concise Binary Object Representation)
The `cbor` library provides a Python implementation of RFC 7049, the Concise Binary Object Representation (CBOR). It allows encoding and decoding Python objects into a compact, binary format, offering an API similar to Python's built-in `json` module. The current version is 1.0.0, released in March 2024, indicating a stable and mature API, with a relatively slow release cadence focused on stability.
Warnings
- breaking Older versions (e.g., pre-0.2.0) of the `cbor` library had minor API changes (e.g., removal of `cbor.MAJOR_TYPE_BITS`, aliasing of `cbor.CBORError`). While the 1.0.0 API is stable, upgrading from very old `0.x` versions might require minor code adjustments.
- gotcha Similar to `json`, `cbor.dumps()` cannot serialize arbitrary Python objects (e.g., custom classes) by default. It only handles built-in types and a few standard library types like `datetime`.
- gotcha The library explicitly supports only Python 3. Despite PyPI metadata listing `requires_python: None`, attempting to use `cbor` in a Python 2 environment will result in import errors or syntax issues.
- gotcha `datetime.datetime` objects are serialized using CBOR tag 0, which represents a standard date/time string (RFC 3339). If you require a different representation, such as a UNIX timestamp or a custom string format, you must convert the `datetime` object manually before serialization.
Install
-
pip install cbor
Imports
- cbor
import cbor
Quickstart
import cbor
import io
import datetime
# Example Python dictionary with various types
data_to_encode = {
'name': 'Alice',
'age': 30,
'is_student': False,
'grades': [95.5, 88, 92.0],
'address': None,
'bio_bytes': b'\x01\x02\x03',
'timestamp': datetime.datetime.now(datetime.timezone.utc).replace(microsecond=0)
}
# 1. Encode to bytes
encoded_bytes = cbor.dumps(data_to_encode)
print(f"Encoded CBOR bytes: {encoded_bytes.hex()}")
# 2. Decode from bytes
decoded_data = cbor.loads(encoded_bytes)
print(f"Decoded data: {decoded_data}")
print(f"Decoded timestamp type: {type(decoded_data['timestamp'])}")
# 3. Encode/Decode using file-like objects (streaming)
buffer = io.BytesIO()
cbor.dump(data_to_encode, buffer)
buffer.seek(0)
stream_decoded_data = cbor.load(buffer)
print(f"Stream decoded data: {stream_decoded_data}")