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.
Install & Compatibility
Where this runs
tested against v6.1.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.925 runs
installs and imports cleanly · install 0.0s · import 0.015s · 19.2MB
glibcpy 3.10–3.925 runs
installs and imports cleanly · install 1.6s · import 0.011s · 20MB
17MB installed
● package 17MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
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
✗ from cbor2.encoder import CBOREncoder
The `cbor2.encoder` module was deprecated in 5.5.0 and will be removed in the next major release (6.x.x). Import directly from `cbor2` instead.
CBORDecoder
✓ from cbor2 import CBORDecoder
✗ from cbor2.decoder import CBORDecoder
The `cbor2.decoder` module was deprecated in 5.5.0 and will be removed in the next major release (6.x.x). Import directly from `cbor2` instead.
This quickstart demonstrates the basic encoding and decoding of Python objects to and from CBOR bytestrings using `cbor2.dumps()` and `cbor2.loads()`.
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}")
Debug
Known issues
breakingThe 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`.fixUpdate imports to load symbols directly from the `cbor2` package (e.g., `from cbor2 import dumps` instead of `from cbor2.encoder import dumps`).
affects: >=5.5.0 (deprecation), upcoming 6.x.x (removal)
breakingVersion 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.fixReview the official `cbor2` documentation for version 6.0.0 for a complete list of breaking changes and adapt custom `tag_hook` and `object_hook` implementations. Avoid direct calls to previously available individual decoding functions.
affects: >=6.0.0
gotchaWhen 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.fixTo encode cyclic data structures, enable value sharing by passing `value_sharing=True` to `cbor2.dumps()` or `cbor2.dump()`. Be aware that support for value sharing may be rare in other CBOR implementations.
affects: all
gotchaWhen 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.fixAlways ensure the encoder or writer is properly closed, either explicitly with `writer.close()` or by using a `with` statement.
affects: all
gotchaDecoding malformed or corrupted CBOR data with `cbor2.loads()` or `cbor2.load()` will raise a `cbor2.CBORDecodeError`, potentially crashing the application if not handled.fixWrap deserialization calls in a `try-except cbor2.CBORDecodeError` block to gracefully handle potential decoding issues and ensure application stability.
affects: all
gotchaWhen 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.fixAlways verify the type of decoded data, especially when dealing with potentially tagged values, and be prepared to handle the appropriate Python object types that `cbor2` maps to standard CBOR tags.
affects: all
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'cbor2'
The cbor2 library is not installed in your current Python environment or is not accessible within your Python path.
fixInstall the cbor2 package using pip: `pip install cbor2`.
cbor2.CBORDecodeError: error reading major type at index X: index out of range
The input byte string provided to cbor2.loads() or cbor2.load() is not valid CBOR data, is corrupted, or is prematurely truncated, leading the decoder to fail when trying to read the next data item.
fixEnsure the input data is a complete and correctly formatted CBOR byte string. Wrap decoding calls in a `try-except cbor2.CBORDecodeError` block to gracefully handle invalid input.
cbor2.CBOREncodeTypeError: type X is not cbor2 encodable
You are attempting to serialize a Python object type (e.g., a custom class instance or certain standard library types) for which cbor2 does not have a default encoding mechanism.
fixProvide a custom encoder function by registering it with the `encoders` argument or by using the `default` argument in `cbor2.dumps()` or `cbor2.dump()` to specify how to handle the unsupported type.
cbor2.CBOREncodeValueError: cyclic data structure detected
The Python object you are trying to encode contains circular references (e.g., an object directly or indirectly references itself), and cbor2's value sharing feature is not enabled to handle such structures.
fixEnable value sharing during encoding by passing `value_sharing=True` to `cbor2.dumps()` or `cbor2.dump()`. For custom types, you may also need to decorate custom encoder and decoder callbacks with `@shareable_encoder` and `@shareable_decoder`.
Audit
Dependencies
No dependency data recorded yet.