# API reference

## Encoding

cbor2.dumps(obj, datetime_as_timestamp=False, timezone=None, value_sharing=False, 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

    - default (`Callable`[[`CBOREncoder`, `Any`], `None`] | `None`) – 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, 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

    - default (`Callable`[[`CBOREncoder`, `Any`], `None`] | `None`) – 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).

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

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

  Return type:

    `None`

class cbor2.CBOREncoder(fp, datetime_as_timestamp=False, timezone=None, value_sharing=False, 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()`.

  disable_string_namespacing()

    Disable generation of new string namespaces for the duration of the context block.

    Return type:

      `Generator`[`None`]

  disable_string_referencing()

    Disable tracking of string references for the duration of the context block.

    Return type:

      `Generator`[`None`]

  disable_value_sharing()

    Disable value sharing in the encoder for the duration of the context block.

    Return type:

      `Generator`[`None`]

  encode(obj)

    Encode the given object using CBOR.

    Parameters:

      obj (`Any`) – the object to encode

    Return type:

      `None`

  encode_canonical_map(value)

    Reorder keys according to Canonical CBOR specification

    Return type:

      `None`

  encode_sortable_key(value)

    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.

    Return type:

      `tuple`[`int`, `bytes`]

  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.

    Return type:

      `bytes`

  write(data)

    Write bytes to the data stream.

    Parameters:

      data (bytes) – the bytes to write

    Return type:

      `None`

@cbor2.shareable_encoder(func)

  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. :rtype: Callable[[cbor2.CBOREncoder, Any], None]

## Decoding

cbor2.loads(s, tag_hook=None, object_hook=None, str_errors='strict')

  Deserialize an object from a bytestring.

  Parameters:

    - s (bytes) – the bytestring to deserialize

    - tag_hook (Callable[[CBORDecoder, CBORTag], Any] | None) – 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 (Callable[[CBORDecoder, dict[Any, Any]], Any] | None) – 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.

    - str_errors (Literal[‘strict’, ‘error’, ‘replace’]) – determines how to handle unicode decoding errors (see the Error Handlers section in the standard library documentation for details)

  Return type:

    Any

  Returns:

    the deserialized object

cbor2.load(fp, tag_hook=None, object_hook=None, str_errors='strict')

  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 (Callable[[CBORDecoder, CBORTag], Any] | None) – 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 (Callable[[CBORDecoder, dict[Any, Any]], Any] | None) – 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.

    - str_errors (Literal[‘strict’, ‘error’, ‘replace’]) – determines how to handle unicode decoding errors (see the Error Handlers section in the standard library documentation for details)

  Return type:

    Any

  Returns:

    the deserialized object

class cbor2.CBORDecoder(fp, tag_hook=None, object_hook=None, str_errors='strict')

  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 points are `decode()` and `decode_from_bytes()`.

  decode()

    Decode the next value from the stream.

    Raises:

      CBORDecodeError – if there is any problem decoding the stream

    Return type:

      `object`

  decode_from_bytes(buf)

    Wrap the given bytestring as a file and call `decode()` with it as the argument.

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

    Return type:

      `object`

  property immutable: bool

    Used by decoders to check if the calling context requires an immutable type. Object_hook or tag_hook should raise an exception if this flag is set unless the result can be safely used as a dict key.

  read(amount)

    Read bytes from the data stream.

    Parameters:

      amount (int) – the number of bytes to read

    Return type:

      `bytes`

  set_shareable(value)

    Set the shareable value for the last encountered shared value marker, if any. If the current shared index is `None`, nothing is done.

    Parameters:

      value (`TypeVar`(`T`)) – the shared value

    Return type:

      `TypeVar`(`T`)

    Returns:

      the shared value to permit chaining

## Types

class cbor2.CBORSimpleValue(value: int)

  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)

cbor2.undefined
A singleton representing the CBOR "undefined" value.

## 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.CBORDecodeValueError

  Raised when the CBOR stream being decoded contains an invalid value.

exception cbor2.CBORDecodeEOF

  Raised when decoding unexpectedly reaches EOF.