Basic usage
Serializing and deserializing with cbor2 is pretty straightforward:
from cbor2 import dump, dumps, load, loads
# Serialize an object as a bytestring
data = dumps(['hello', 'world'])
# Deserialize a bytestring
obj = loads(data)
# Efficiently deserialize from a file
with open('input.cbor', 'rb') as fp:
obj = load(fp)
# Efficiently serialize an object to a file
with open('output.cbor', 'wb') as fp:
dump(obj, fp)
Some data types, however, require extra considerations, as detailed below.
Decoding concatenated objects
A CBOR sequence consists of encoded objects concatenated without separators. To decode
one object at a time, use a CBORDecoder and check for EOF between objects:
from cbor2 import CBORDecoder
def decode_sequence(fp):
decoder = CBORDecoder(fp)
while fp.peek(1):
yield decoder.decode()
For a file containing a CBOR sequence:
with open("sequence.cbor", "rb") as fp:
for value in decode_sequence(fp):
print(value)
For bytes already in memory, wrap io.BytesIO to provide peek():
from io import BufferedReader, BytesIO
from cbor2 import dumps
data = dumps(1) + dumps("hello") + dumps(None)
with BufferedReader(BytesIO(data)) as fp:
print(list(decode_sequence(fp))) # [1, 'hello', None]
This recipe expects a blocking binary io.BufferedReader, such as the file returned
by open(path, "rb"). Check and decode through the same buffered stream, not its underlying
raw stream. On seekable streams, the decoder may read ahead and then seek back after each
object; on non-seekable streams, it reads only the bytes needed for that object.
An empty stream yields no objects. Do not catch CBORDecodeEOF to end the loop:
EOF during an object means truncated data and must remain an error. Malformed objects likewise
raise CBORDecodeError. This is not a recipe for non-blocking input: a temporary lack of
bytes is not the end of the sequence.
Date/time handling
The CBOR specification does not support naïve datetimes (that is, datetimes where tzinfo is
missing). When the encoder encounters such a datetime, it needs to know which timezone it belongs
to. To this end, you can specify a default timezone by passing a tzinfo instance
to dump()/dumps() call as the timezone argument.
Decoded datetimes are always timezone aware.
By default, datetimes are serialized in a manner that retains their timezone offsets. You can
optimize the data stream size by passing datetime_as_timestamp=False to
dump()/dumps(), but this causes the timezone offset
information to be lost.
In versions prior to 4.2 the encoder would convert a datetime.date object into a
datetime.datetime prior to writing. This can cause confusion on decoding so this has been
disabled by default in the next version. The behaviour can be re-enabled as follows:
from cbor2 import dumps
from datetime import date, timezone
# Serialize dates as datetimes
encoded = dumps(date(2019, 10, 28), timezone=timezone.utc, date_as_datetime=True)
A default timezone offset must be provided also.
Cyclic (recursive) data structures
If the encoder encounters a shareable object (ie. list or dict) that it has seen before, it will
by default raise CBOREncodeError indicating that a cyclic reference has been
detected and value sharing was not enabled. CBOR has, however, an extension specification that
allows the encoder to reference a previously encoded value without processing it again. This makes
it possible to serialize such cyclic references, but value sharing has to be enabled by passing
value_sharing=True to dump()/dumps().
Warning
Support for value sharing is rare in other CBOR implementations, so think carefully whether you want to enable it. It also causes some line overhead, as all potentially shareable values must be tagged as such.
String references
When string_referencing=True is passed to
dump()/dumps(), if the encoder would encode a string that
it has previously encoded and where a reference would be shorter than the encoded string, it
instead encodes a reference to the nth sufficiently long string already encoded.
Warning
Support for string referencing is rare in other CBOR implementations, so think carefully whether you want to enable it.
Encoder support for built-in CBOR types
Below is the list of Python types encoded as various major CBOR tags or special values.
Python type |
Major tag |
Subtype |
|---|---|---|
0 or 1 |
||
2 |
||
2 |
||
3 |
||
4 |
||
4 |
||
4 |
||
5 |
||
5 |
||
7 |
20 ( |
|
7 |
22 |
|
7 |
23 |
|
7 |
27 |
Encoder semantic tag support
Below is the list of Python types and the semantic tags they’re encoded as.
Python type |
Semantic tag |
|---|---|
43000 |
|
0 or 1, depending on the
|
|
1004, 100, 1 or 0, depending on the
|
|
4 (unless NaN or infinities, which are encoded as floats) |
|
30 |
|
258 |
|
35 |
|
35 |
|
52 |
|
52 |
|
52 |
|
54 |
|
54 |
|
54 |
|
258 |
|
37 |
If you want to write a file that is detected as CBOR by the Unix file utility, wrap your data
in a CBORTag object like so:
from cbor2 import dump, CBORTag
with open('output.cbor', 'wb') as fp:
dump(CBORTag(55799, obj), fp)
This will be ignored on decode and the original data content will be returned.
Use Cases
Here are some things that the cbor2 library could be (and in some cases, is being) used for:
Experimenting with network protocols based on CBOR encoding
Designing new data storage formats
Submitting binary documents to ElasticSearch without base64 encoding overhead
Storing and validating file metadata in a secure backup system
RPC which supports Decimals with low overhead