CBOR (de)serializer with extensive tag support
cbor2 is a Python library for encoding and decoding Concise Binary Object Representation (CBOR) data, fully compatible with RFC 8949. It offers a simple API similar to the `json` or `pickle` modules, with extensive support for CBOR tags and standard library objects. Currently at version 5.9.0, it is actively maintained with a regular release cadence, featuring a highly performant Rust-based backend for improved memory safety and performance.
Warnings
- breaking The modules `cbor2.encoder`, `cbor2.decoder`, and `cbor2.types` have been deprecated since version 5.5.0 and will be removed in the upcoming 6.x.x major release. Direct imports from these modules will cause `ModuleNotFoundError`.
- breaking Version 6.0.0 (currently in release candidate) introduces several backward-incompatible changes, including signature changes for `tag_hook` and `object_hook` decoder callables, removal of `break_marker`, changes in IP address encoding tags, and removal of individual decoding functions from the API.
- gotcha When encoding Python objects with cyclic references (e.g., lists or dictionaries that refer back to themselves), `cbor2` will raise a `CBOREncodeError` by default. CBOR supports shared value references as an extension.
- gotcha When using `CBOREncoder` or `CBORWriter` for streaming (e.g., writing to a file), forgetting to call `close()` can result in truncated or incomplete CBOR data. The `with` statement handles this automatically.
- gotcha Decoding malformed or corrupted CBOR data with `cbor2.loads()` or `cbor2.load()` will raise a `cbor2.CBORDecodeError`, potentially crashing the application if not handled.
- gotcha When decoding CBOR, a value that appears simple (like a string or integer) might actually be a CBOR-tagged type (e.g., a `datetime` object for a timestamp tag). If your code expects a specific simple Python type, this can lead to runtime errors.
Install
-
pip install cbor2
Imports
- dumps
from cbor2 import dumps
- loads
from cbor2 import loads
- dump
from cbor2 import dump
- load
from cbor2 import load
- CBOREncoder
from cbor2 import CBOREncoder
- CBORDecoder
from cbor2 import CBORDecoder
Quickstart
import cbor2
data_to_encode = {'name': 'Alice', 'age': 30, 'is_active': True}
# Encode Python object to CBOR bytestring
encoded_data = cbor2.dumps(data_to_encode)
print(f"Encoded CBOR: {encoded_data}")
# Decode CBOR bytestring back to Python object
decoded_data = cbor2.loads(encoded_data)
print(f"Decoded Python object: {decoded_data}")
# Example with file-like objects
# import io
# output_buffer = io.BytesIO()
# cbor2.dump(data_to_encode, output_buffer)
# output_buffer.seek(0)
# decoded_from_file = cbor2.load(output_buffer)
# print(f"Decoded from file-like object: {decoded_from_file}")