API reference

Encoding

cbor2.dumps(obj, *, datetime_as_timestamp=False, timezone=None, value_sharing=False, encoders=None, default=None, canonical=False, date_as_datetime=False, string_referencing=False, indefinite_containers=False)

Serialize an object to a bytestring.

Parameters:
  • obj (object) – the object to serialize

  • datetime_as_timestamp (bool) – set to True to serialize datetimes as UNIX timestamps (this makes datetimes more concise on the wire, but loses the timezone information)

  • timezone (tzinfo | None) – the default timezone to use for serializing naive datetimes; if this is not specified naive datetimes will throw a ValueError when encoding is attempted

  • value_sharing (bool) – set to True to allow more efficient serializing of repeated values and, more importantly, cyclic data structures, at the cost of extra line overhead

  • encoders (Mapping[type, EncoderHook] | None) – An optional mapping for overriding the encoding for select Python types. Each key in this mapping should be a Python type object, and the value a callable that takes two arguments: the encoder object and the object to encode.

  • default (Optional[EncoderHook]) – a callable that is called by the encoder with two arguments (the encoder instance and the value being encoded) when no suitable encoder has been found, and should use the methods on the encoder to encode any objects it wants to add to the data stream

  • canonical (bool) – when True, use “canonical” CBOR representation; this typically involves sorting maps, sets, etc. into a pre-determined order ensuring that serializations are comparable without decoding

  • date_as_datetime (bool) – set to True to serialize date objects as datetimes (CBOR tag 0), which was the default behavior in previous releases (cbor2 <= 4.1.2).

  • string_referencing (bool) – set to True to allow more efficient serializing of repeated string values

  • indefinite_containers (bool) – encode containers as indefinite (use stop code instead of specifying length)

Return type:

bytes

Returns:

the serialized output

cbor2.dump(obj, fp, *, datetime_as_timestamp=False, timezone=None, value_sharing=False, encoders=None, default=None, canonical=False, date_as_datetime=False, string_referencing=False, indefinite_containers=False)

Serialize an object to a file.

Parameters:
  • obj (object) – the object to serialize

  • fp (IO[bytes]) – the file to write to (any file-like object opened for writing in binary mode)

  • datetime_as_timestamp (bool) – set to True to serialize datetimes as UNIX timestamps (this makes datetimes more concise on the wire, but loses the timezone information)

  • timezone (tzinfo | None) – the default timezone to use for serializing naive datetimes; if this is not specified naive datetimes will throw a ValueError when encoding is attempted

  • value_sharing (bool) – set to True to allow more efficient serializing of repeated values and, more importantly, cyclic data structures, at the cost of extra line overhead

  • encoders (Mapping[type, EncoderHook] | None) – An optional mapping for overriding the encoding for select Python types. Each key in this mapping should be a Python type object, and the value a callable that takes two arguments: the encoder object and the object to encode.

  • default (Optional[EncoderHook]) – a callable that is called by the encoder with two arguments (the encoder instance and the value being encoded) when no suitable encoder has been found, and should use the methods on the encoder to encode any objects it wants to add to the data stream

  • canonical (bool) – when True, use “canonical” CBOR representation; this typically involves sorting maps, sets, etc. into a pre-determined order ensuring that serializations are comparable without decoding

  • date_as_datetime (bool) – set to True to serialize date objects as datetimes (CBOR tag 0), which was the default behavior in previous releases (cbor2 <= 4.1.2).

  • string_referencing (bool) – set to True to allow more efficient serializing of repeated string values

  • indefinite_containers (bool) – encode containers as indefinite (use stop code instead of specifying length)

Return type:

None

class cbor2.CBOREncoder(fp, *, datetime_as_timestamp=False, timezone=None, value_sharing=False, encoders=None, default=None, canonical=False, date_as_datetime=False, string_referencing=False, indefinite_containers=False)

The CBOREncoder class implements a fully featured CBOR encoder with several extensions for handling shared references, big integers, rational numbers, and so on. Typically, the class is not used directly, but the dump() and dumps() functions are called to indirectly construct and use the class.

When the class is constructed manually, the main entry points are encode() and encode_to_bytes().

Parameters:
  • fp (IO[bytes]) – the file to write to (any file-like object opened for writing in binary mode)

  • datetime_as_timestamp (bool) – set to True to serialize datetimes as UNIX timestamps (this makes datetimes more concise on the wire, but loses the timezone information)

  • timezone (tzinfo | None) – the default timezone to use for serializing naive datetimes; if this is not specified naive datetimes will throw a ValueError when encoding is attempted

  • value_sharing (bool) – set to True to allow more efficient serializing of repeated values and, more importantly, cyclic data structures, at the cost of extra line overhead

  • encoders (Mapping[type, EncoderHook] | None) – An optional mapping for overriding the encoding for select Python types. Each key in this mapping should be a Python type object, and the value a callable that takes two arguments: the encoder object and the object to encode.

  • default (Optional[EncoderHook]) – a callable that is called by the encoder with two arguments (the encoder instance and the value being encoded) when no suitable encoder has been found, and should use the methods on the encoder to encode any objects it wants to add to the data stream

  • canonical (bool) – when True, use “canonical” CBOR representation; this typically involves sorting maps, sets, etc. into a pre-determined order ensuring that serializations are comparable without decoding

  • date_as_datetime (bool) – set to True to serialize date objects as datetimes (CBOR tag 0), which was the default behavior in previous releases (cbor2 <= 4.1.2).

  • string_referencing (bool) – set to True to allow more efficient serializing of repeated string values

  • indefinite_containers (bool) – encode containers as indefinite (use stop code instead of specifying length)

encode(obj, /)

Encode the given object using CBOR.

Parameters:

obj (object) – the object to encode

Return type:

None

encode_semantic(tag, value)

Encode a value with a semantic tag.

Parameters:
  • tag (int) – a numeric tag value

  • value (Any) – the object to be encoded

Return type:

None

encode_sortable_item(item)

Takes a (key, value) tuple and calculates the length of its optimal byte representation, along with the representation itself. This is used as the sorting key in CBOR’s canonical representations.

Parameters:

item – a (key, value) tuple

encode_sortable_key(key)

Takes a key and calculates the length of its optimal byte representation, along with the representation itself. This is used as the sorting key in CBOR’s canonical representations.

encode_to_bytes(obj, /)

Encode the given object to a byte buffer and return its value as bytes.

This method was intended to be used from the default hook when an object needs to be encoded separately from the rest but while still taking advantage of the shared value registry.

Parameters:

obj (object) – the object to encode

Return type:

bytes

write(buf, /)

Write bytes to the data stream.

Parameters:

buf (bytes) – the bytes to write

Return type:

int

Returns:

the number of bytes written

Note

During the encoding of an object, this method may write the given bytes to the internal buffer without flushing to the actual output stream. When called outside the encoding process, it is equivalent to encoder.fp.write(...).

@cbor2.shareable_encoder

Wrap the given encoder function to gracefully handle cyclic data structures.

If value sharing is enabled, this marks the given value shared in the datastream on the first call. If the value has already been passed to this method, a reference marker is instead written to the data stream and the wrapped function is not called.

If value sharing is disabled, only infinite recursion protection is done.

Return type:

Callable[[CBOREncoder, TypeVar(_T)], None]

Decoding

cbor2.loads(data, *, tag_hook=None, object_hook=None, semantic_decoders=None, str_errors='strict', max_depth=400, allow_indefinite=True, allow_duplicate_keys=True, immutable=False)

Deserialize an object from a bytestring.

Parameters:
  • data (Buffer) –

    the bytestring (or any object implementing the buffer protocol) to deserialize

    Note

    Types other than bytes will be converted to bytes, involving memory copying.

  • tag_hook (Optional[TagHook]) – callable that takes 2 arguments: the decoder instance, and the CBORTag to be decoded. This callback is invoked for any tags for which there is no built-in decoder. The return value is substituted for the CBORTag object in the deserialized output

  • object_hook (Optional[ObjectHook]) – callable that takes 2 arguments: the decoder instance, and a dictionary. This callback is invoked for each deserialized dict object. The return value is substituted for the dict in the deserialized output.

  • semantic_decoders (Mapping[int, Union[SemanticDecoderCallback, ShareableDecoderInitializer]] | None) – An optional mapping for overriding the decoding for select semantic tags. The value is a mapping of semantic tags (integers) to callables that take the decoder instance as the sole argument.

  • str_errors (str) – determines how to handle unicode decoding errors (see the Error Handlers section in the standard library documentation for details)

  • max_depth (int) – maximum allowed depth for nested containers

  • allow_indefinite (bool) – if False, raise a CBORDecodeError when encountering an indefinite-length string or container in the input stream

  • allow_duplicate_keys (bool) – if False, raise a CBORDecodeError when a map key that has already been decoded in the same map is encountered

  • immutable (bool) – if True, return immutable objects (e.g. frozenset and tuple) instead of mutable objects (e.g. list and dict)

Return type:

Any

Returns:

the deserialized object

cbor2.load(fp, *, tag_hook=None, object_hook=None, semantic_decoders=None, str_errors='strict', read_size=4096, max_depth=400, allow_indefinite=True, allow_duplicate_keys=True, immutable=False)

Deserialize an object from an open file.

Parameters:
  • fp (IO[bytes]) – the file to read from (any file-like object opened for reading in binary mode)

  • tag_hook (Optional[TagHook]) – callable that takes 2 arguments: the decoder instance, and the CBORTag to be decoded. This callback is invoked for any tags for which there is no specific decoder. The return value is substituted for the CBORTag object in the deserialized output

  • object_hook (Optional[ObjectHook]) – callable that takes 2 arguments: the decoder instance, and a dictionary. This callback is invoked for each deserialized dict object. The return value is substituted for the dict in the deserialized output.

  • semantic_decoders (Mapping[int, Union[SemanticDecoderCallback, ShareableDecoderInitializer]] | None) – An optional mapping for overriding the decoding for select semantic tags. The value is a mapping of semantic tags (integers) to callables that take the decoder instance as the sole argument.

  • str_errors (str) – determines how to handle unicode decoding errors (see the Error Handlers section in the standard library documentation for details)

  • read_size (int) – minimum amount of bytes to read at once (ignored if fp is not seekable)

  • max_depth (int) – maximum allowed depth for nested containers

  • allow_indefinite (bool) – if False, raise a CBORDecodeError when encountering an indefinite-length string or container in the input stream

  • allow_duplicate_keys (bool) – if False, raise a CBORDecodeError when a map key that has already been decoded in the same map is encountered

  • immutable (bool) – if True, return immutable objects (e.g. frozenset and tuple) instead of mutable objects (e.g. list and dict)

Return type:

Any

Returns:

the deserialized object

class cbor2.CBORDecoder(fp, *, tag_hook=None, object_hook=None, semantic_decoders=None, str_errors='strict', read_size=4096, max_depth=400, allow_indefinite=True, allow_duplicate_keys=True)

The CBORDecoder class implements a fully featured CBOR decoder with several extensions for handling shared references, big integers, rational numbers and so on. Typically, the class is not used directly, but the load() and loads() functions are called to indirectly construct and use the class.

When the class is constructed manually, the main entry point is decode().

Parameters:
  • fp (IO[bytes]) – the file to read from (any file-like object opened for reading in binary mode)

  • tag_hook (Optional[TagHook]) – callable that takes 2 arguments: the decoder instance, and the CBORTag to be decoded. This callback is invoked for any tags for which there is no built-in decoder. The return value is substituted for the CBORTag object in the deserialized output

  • object_hook (Optional[ObjectHook]) – callable that takes 2 arguments: the decoder instance, and a dictionary. This callback is invoked for each deserialized dict object. The return value is substituted for the dict in the deserialized output.

  • semantic_decoders (Mapping[int, Union[SemanticDecoderCallback, ShareableDecoderInitializer]] | None) – An optional mapping for overriding the decoding for select semantic tags. The value is a mapping of semantic tags (integers) to callables that take the decoder instance as the sole argument.

  • str_errors (str) – determines how to handle Unicode decoding errors (see the Error Handlers section in the standard library documentation for details)

  • read_size (int) – minimum number of bytes to read at once (ignored if fp is not seekable)

  • max_depth (int) – maximum allowed depth for nested containers

  • allow_indefinite (bool) – if False, raise a CBORDecodeError when encountering an indefinite-length string or container in the input stream

  • allow_duplicate_keys (bool) – if False, raise a CBORDecodeError when a map key that has already been decoded in the same map is encountered

decode(*, immutable=False)

Decode the next value from the stream.

Parameters:

immutable (bool) – if True, decode the next item as an immutable type (e.g. tuple instead of a list), if possible

Return type:

Any

Returns:

the decoded object

Raises:

CBORDecodeError – if there is any problem decoding the stream

read(amount, /)

Read bytes from the data stream.

Parameters:

amount (int) – the number of bytes to read

Return type:

bytes

@cbor2.shareable_decoder(func=None, /, *, name=None, immutable=False)

Decorates a function to be a two-stage decoder.

Parameters:
  • name – the name displayed in a CBORDecodeError raised by the decoder (e.g. “error decoding thingamajig”) where name=’thingamajig`)

  • immutableTrue if the item sent to the decoder should be decoded as immutable

Return type:

ShareableDecoderInitializer

Types

class cbor2.CBORSimpleValue(value)

Represents a CBOR “simple value”.

Parameters:

value (int) – the value (0-255)

class cbor2.CBORTag(tag, value)

Represents a CBOR semantic tag.

Parameters:
  • tag (int) – tag number

  • value (Any) – encapsulated value (any object)

class cbor2.frozendict(*args, **kwargs)

A hashable, immutable mapping type.

The arguments to FrozenDict are processed just like those to dict.

Available only on Python 3.14 and below. On Python 3.15, the decoder uses the built-in frozendict class instead.

cbor2.undefined

A singleton representing the CBOR “undefined” value.

Type aliases

type SemanticDecoderCallback = Callable[[Any, bool], Any]

The common type of callbacks accepted in the semantic_decoders decoder option.

type ShareableDecoderInitializer = Callable[[bool], tuple[Any, ShareableDecoderCallback]]

A two-phase decoder callback accepted in the semantic_decoders decoder option.

type ShareableDecoderCallback = Callable[[Any], Any]

Type of the callback returned by a ShareableDecoderInitializer

type ObjectHook = Callable[[collections.abc.Mapping[Any, Any]], Any]

Type of the callback needed for the object_hook decoder option.

type TagHook = Callable[[CBORTag], Any]

Type of the callback needed for the tag_hook decoder option.

type EncoderHook = Callable[[CBOREncoder, Any], Any]

Type of the callback needed for the default encoder option.

Exceptions

exception cbor2.CBORError

Base class for errors that occur during CBOR encoding or decoding.

exception cbor2.CBOREncodeError

Raised for exceptions occurring during CBOR encoding.

exception cbor2.CBOREncodeTypeError

Raised when attempting to encode a type that cannot be serialized.

exception cbor2.CBOREncodeValueError

Raised when the CBOR encoder encounters an invalid value.

exception cbor2.CBORDecodeError

Raised for exceptions occurring during CBOR decoding.

exception cbor2.CBORDecodeEOF

Raised when decoding unexpectedly reaches EOF.