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 serializedatetime_as_timestamp (
bool) – set toTrueto 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 aValueErrorwhen encoding is attemptedvalue_sharing (
bool) – set toTrueto allow more efficient serializing of repeated values and, more importantly, cyclic data structures, at the cost of extra line overheadencoders (
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 streamcanonical (
bool) – whenTrue, use “canonical” CBOR representation; this typically involves sorting maps, sets, etc. into a pre-determined order ensuring that serializations are comparable without decodingdate_as_datetime (
bool) – set toTrueto serialize date objects as datetimes (CBOR tag 0), which was the default behavior in previous releases (cbor2 <= 4.1.2).string_referencing (
bool) – set toTrueto allow more efficient serializing of repeated string valuesindefinite_containers (
bool) – encode containers as indefinite (use stop code instead of specifying length)
- Return type:
- 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 serializefp (
IO[bytes]) – the file to write to (any file-like object opened for writing in binary mode)datetime_as_timestamp (
bool) – set toTrueto 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 aValueErrorwhen encoding is attemptedvalue_sharing (
bool) – set toTrueto allow more efficient serializing of repeated values and, more importantly, cyclic data structures, at the cost of extra line overheadencoders (
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 streamcanonical (
bool) – whenTrue, use “canonical” CBOR representation; this typically involves sorting maps, sets, etc. into a pre-determined order ensuring that serializations are comparable without decodingdate_as_datetime (
bool) – set toTrueto serialize date objects as datetimes (CBOR tag 0), which was the default behavior in previous releases (cbor2 <= 4.1.2).string_referencing (
bool) – set toTrueto allow more efficient serializing of repeated string valuesindefinite_containers (
bool) – encode containers as indefinite (use stop code instead of specifying length)
- Return type:
- 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()andencode_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 toTrueto 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 aValueErrorwhen encoding is attemptedvalue_sharing (
bool) – set toTrueto allow more efficient serializing of repeated values and, more importantly, cyclic data structures, at the cost of extra line overheadencoders (
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 streamcanonical (
bool) – whenTrue, use “canonical” CBOR representation; this typically involves sorting maps, sets, etc. into a pre-determined order ensuring that serializations are comparable without decodingdate_as_datetime (
bool) – set toTrueto serialize date objects as datetimes (CBOR tag 0), which was the default behavior in previous releases (cbor2 <= 4.1.2).string_referencing (
bool) – set toTrueto allow more efficient serializing of repeated string valuesindefinite_containers (
bool) – encode containers as indefinite (use stop code instead of specifying length)
- encode(obj, /)
Encode the given object using CBOR.
- encode_semantic(tag, value)
Encode a value with a semantic tag.
- 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
defaulthook when an object needs to be encoded separately from the rest but while still taking advantage of the shared value registry.
- write(buf, /)
Write bytes to the data stream.
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(...).
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
tag_hook (
Optional[TagHook]) – callable that takes 2 arguments: the decoder instance, and theCBORTagto be decoded. This callback is invoked for any tags for which there is no built-in decoder. The return value is substituted for theCBORTagobject in the deserialized outputobject_hook (
Optional[ObjectHook]) – callable that takes 2 arguments: the decoder instance, and a dictionary. This callback is invoked for each deserializeddictobject. 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 containersallow_indefinite (
bool) – ifFalse, raise aCBORDecodeErrorwhen encountering an indefinite-length string or container in the input streamallow_duplicate_keys (
bool) – ifFalse, raise aCBORDecodeErrorwhen a map key that has already been decoded in the same map is encounteredimmutable (
bool) – ifTrue, return immutable objects (e.g.frozensetandtuple) instead of mutable objects (e.g.listanddict)
- Return type:
- 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 theCBORTagto be decoded. This callback is invoked for any tags for which there is no specific decoder. The return value is substituted for theCBORTagobject in the deserialized outputobject_hook (
Optional[ObjectHook]) – callable that takes 2 arguments: the decoder instance, and a dictionary. This callback is invoked for each deserializeddictobject. 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 iffpis not seekable)max_depth (
int) – maximum allowed depth for nested containersallow_indefinite (
bool) – ifFalse, raise aCBORDecodeErrorwhen encountering an indefinite-length string or container in the input streamallow_duplicate_keys (
bool) – ifFalse, raise aCBORDecodeErrorwhen a map key that has already been decoded in the same map is encounteredimmutable (
bool) – ifTrue, return immutable objects (e.g.frozensetandtuple) instead of mutable objects (e.g.listanddict)
- Return type:
- 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()andloads()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 theCBORTagto be decoded. This callback is invoked for any tags for which there is no built-in decoder. The return value is substituted for theCBORTagobject in the deserialized outputobject_hook (
Optional[ObjectHook]) – callable that takes 2 arguments: the decoder instance, and a dictionary. This callback is invoked for each deserializeddictobject. 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 iffpis not seekable)max_depth (
int) – maximum allowed depth for nested containersallow_indefinite (
bool) – ifFalse, raise aCBORDecodeErrorwhen encountering an indefinite-length string or container in the input streamallow_duplicate_keys (
bool) – ifFalse, raise aCBORDecodeErrorwhen a map key that has already been decoded in the same map is encountered
- decode(*, immutable=False)
Decode the next value from the stream.
Decorates a function to be a two-stage decoder.
- Parameters:
name – the name displayed in a
CBORDecodeErrorraised by the decoder (e.g. “error decoding thingamajig”) where name=’thingamajig`)immutable –
Trueif the item sent to the decoder should be decoded as immutable
- Return type:
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.
- class cbor2.frozendict(*args, **kwargs)
A hashable, immutable mapping type.
The arguments to
FrozenDictare processed just like those todict.Available only on Python 3.14 and below. On Python 3.15, the decoder uses the built-in
frozendictclass 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_decodersdecoder option.
A two-phase decoder callback accepted in the
semantic_decodersdecoder option.
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_hookdecoder option.
- type TagHook = Callable[[CBORTag], Any]
Type of the callback needed for the
tag_hookdecoder option.
- type EncoderHook = Callable[[CBOREncoder, Any], Any]
Type of the callback needed for the
defaultencoder 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.