logo
CBOR.py - Python API for CBOR

Table of Contents

n/a1.  Introduction
n/a2.  CBOR Wrapper Objects
n/a2.1.  CBOR.Int
n/a2.1.1.  CBOR.Int Methods
n/a2.1.1.1.  get_int8()
n/a2.1.1.2.  get_uint8()
n/a2.1.1.3.  get_int16()
n/a2.1.1.4.  get_uint16()
n/a2.1.1.5.  get_int32()
n/a2.1.1.6.  get_uint32()
n/a2.1.1.7.  get_int53()
n/a2.1.1.8.  get_int64()
n/a2.1.1.9.  get_uint64()
n/a2.1.1.10.  get_int128()
n/a2.1.1.11.  get_uint128()
n/a2.1.1.12.  get_big_int()
n/a2.1.1.13.  CBOR.Int.create_int8()
n/a2.1.1.14.  CBOR.Int.create_uint8()
n/a2.1.1.15.  CBOR.Int.create_int16()
n/a2.1.1.16.  CBOR.Int.create_uint16()
n/a2.1.1.17.  CBOR.Int.create_int32()
n/a2.1.1.18.  CBOR.Int.create_uint32()
n/a2.1.1.19.  CBOR.Int.create_int53()
n/a2.1.1.20.  CBOR.Int.create_int64()
n/a2.1.1.21.  CBOR.Int.create_uint64()
n/a2.1.1.22.  CBOR.Int.create_int128()
n/a2.1.1.23.  CBOR.Int.create_uint128()
n/a2.2.  CBOR.Float
n/a2.2.1.  CBOR.Float Methods
n/a2.2.1.1.  get_float16()
n/a2.2.1.2.  get_float32()
n/a2.2.1.3.  get_float64()
n/a2.2.1.4.  CBOR.Float.create_extended_float()
n/a2.2.1.5.  get_extended_float64()
n/a2.2.1.6.  CBOR.Float.create_float16()
n/a2.2.1.7.  CBOR.Float.create_float32()
n/a2.2.2.  CBOR.Float Properties
n/a2.2.2.1.  length
n/a2.3.  CBOR.NonFinite
n/a2.3.1.  CBOR.NonFinite Methods
n/a2.3.1.1.  get_non_finite()
n/a2.3.1.2.  get_non_finite64()
n/a2.3.1.3.  is_nan()
n/a2.3.1.4.  is_simple()
n/a2.3.1.5.  get_sign()
n/a2.3.1.6.  set_sign()
n/a2.3.1.7.  CBOR.NonFinite.create_payload()
n/a2.3.1.8.  get_payload()
n/a2.3.2.  CBOR.NonFinite Properties
n/a2.3.2.1.  length
n/a2.4.  CBOR.String
n/a2.4.1.  CBOR.String Methods
n/a2.4.1.1.  get_string()
n/a2.5.  CBOR.Bytes
n/a2.5.1.  CBOR.Bytes Methods
n/a2.5.1.1.  get_bytes()
n/a2.6.  CBOR.Boolean
n/a2.6.1.  CBOR.Boolean Methods
n/a2.6.1.1.  get_boolean()
n/a2.7.  CBOR.Null
n/a2.8.  CBOR.Array
n/a2.8.1.  CBOR.Array Methods
n/a2.8.1.1.  add()
n/a2.8.1.2.  get()
n/a2.8.1.3.  remove()
n/a2.8.1.4.  update()
n/a2.8.1.5.  insert()
n/a2.8.1.6.  to_array()
n/a2.8.1.7.  encode_as_sequence()
n/a2.8.2.  CBOR.Array Properties
n/a2.8.2.1.  length
n/a2.9.  CBOR.Map
n/a2.9.1.  CBOR.Map Methods
n/a2.9.1.1.  set()
n/a2.9.1.2.  get()
n/a2.9.1.3.  get_conditionally()
n/a2.9.1.4.  contains_key()
n/a2.9.1.5.  remove()
n/a2.9.1.6.  set_dynamic()
n/a2.9.1.7.  merge()
n/a2.9.1.8.  update()
n/a2.9.1.9.  get_keys()
n/a2.9.1.10.  set_sorting_mode()
n/a2.9.2.  CBOR.Map Properties
n/a2.9.2.1.  length
n/a2.10.  CBOR.Tag
n/a2.10.1.  CBOR.Tag Methods
n/a2.10.1.1.  get()
n/a2.10.1.2.  get_tag_number()
n/a2.10.1.3.  CBOR.Tag.create_cotx_tag()
n/a2.10.2.  CBOR.Tag Properties
n/a2.10.2.1.  cotx_id
n/a2.10.2.2.  cotx_object
n/a2.11.  CBOR.Simple
n/a2.11.1.  CBOR.Simple Methods
n/a2.11.1.1.  get_simple()
n/a3.  Time Objects
n/a3.1.  get_date_time()
n/a3.2.  get_epoch_time()
n/a4.  Common Wrapper Methods
n/a4.1.  encode()
n/a4.2.  clone()
n/a4.3.  equals()
n/a4.4.  to_diagnostic()
n/a4.5.  to_string()
n/a4.6.  is_null()
n/a4.7.  check_for_unread()
n/a4.8.  scan()
n/a5.  Decoding CBOR
n/a5.1.  CBOR.decode()
n/a5.2.  CBOR.init_decoder()
n/a5.3.  Decoder.set_max_nesting_level()
n/a5.4.  Decoder.decode_with_options()
n/a5.5.  Decoder.get_byte_count()
n/a5.6.  CBOR.from_diagnostic()
n/a5.7.  CBOR.from_diagnostic_seq()
n/a6.  Utility Methods
n/a6.1.  CBOR.create_date_time()
n/a6.2.  CBOR.create_epoch_time()
n/a7.  CBOR Numbers
n/a7.1.  Integers
n/a7.2.  Floating-Point Numbers
n/a8.  Diagnostic Notation
n/a9.  Deterministic Encoding
n/a10.  Using the CBOR API
n/a10.1.  Encode CBOR Data
n/a10.2.  Decode CBOR Data
n/a10.3.  Decode Variant CBOR Data
n/a10.4.  Decode CBOR Diagnostic Notation
n/a10.5.  Encode CBOR Sequence
n/a10.6.  Decode CBOR Sequence
n/a11.  Error Handling
n/a12.  Version

1.  Introduction

This document describes a Python API for encoding and decoding CBOR [RFC8949link] data using the [CBOR::Corelink] cross platform profile. The API loosely mimics the "JSON" object by exposing a single global object, unsurprisingly named "CBOR". To minimize the need for application developers having detailed knowledge of CBOR, the CBOR.py API provides a set of high-level wrapper objects. The wrapper objects are used for encoding CBOR data items, as well as being the result of CBOR decoding. The CBOR.py API provides some specific features including:

Note: in this specification CBOR data items are subsequently referred to as "CBOR objects".

Although this document describes a Python API, it may also serve as a guide for CBOR::Core implementations for other software platforms.

2.  CBOR Wrapper Objects

This section describes the wrapper objects and their specific methods. Note that using the "new" operator with a wrapper object is flagged as an error. The following table lists the wrapper objects and their relation to the CBOR objects (here expressed in CDDL [RFC8610link] notation) supported by this specification:
CDDLWrapper ObjectPythonNotes
integer CBOR.Int int 1
float CBOR.Float float 2, 3
CBOR.NonFinite int 3
bstr CBOR.Bytes bytes
tstr CBOR.String str
bool CBOR.Boolean bool
null CBOR.Null
[] CBOR.Array
{} CBOR.Map
#6.n CBOR.Tag
#7.n CBOR.Simple
  1. See also Integers.
  2. See also Floating-Point Numbers.
  3. See also Non-Finite Numbers.

The wrapper concept adds strict type checking to the API. That is, if an application expects a CBOR integer and calls get_int32(), a CBOR.Exception will be thrown if the referenced object is not an instance of CBOR.Int or if the CBOR integer is out of range for signed 32-bit objects.

See also Common Wrapper Methods and Time Objects.

2.1.  CBOR.Int

SyntaxCBOR.Int(value)
DescriptionConstructor. Creates a CBOR integer object.
See also Integer Numbers.
For fine-grained control of programmatically created integers, a set of CBOR.Int.create*() methods are provided as an alternative to the constructor. Note that these methods do not change data; they only verify that data is within expected limits, and if that is the case, finish the operation using the standard constructor.
ParameterTypeDescription
valueintInteger to be wrapped.
ReturnsDescription
CBOR.IntObject.

2.1.1.  CBOR.Int Methods

2.1.1.1.  get_int8()

Syntaxget_int8()
DescriptionGet CBOR int8 object.
If the return value is outside the range -0x80 to 0x7f, a CBOR.Exception is thrown.
ReturnsDescription
intDecoded integer.

2.1.1.2.  get_uint8()

Syntaxget_uint8()
DescriptionGet CBOR uint8 object.
If the return value is outside the range 0 to 0xff, a CBOR.Exception is thrown.
ReturnsDescription
intDecoded integer.

2.1.1.3.  get_int16()

Syntaxget_int16()
DescriptionGet CBOR int16 object.
If the return value is outside the range -0x8000 to 0x7fff, a CBOR.Exception is thrown.
ReturnsDescription
intDecoded integer.

2.1.1.4.  get_uint16()

Syntaxget_uint16()
DescriptionGet CBOR uint16 object.
If the return value is outside the range 0 to 0xffff, a CBOR.Exception is thrown.
ReturnsDescription
intDecoded integer.

2.1.1.5.  get_int32()

Syntaxget_int32()
DescriptionGet CBOR int32 object.
If the return value is outside the range -0x80000000 to 0x7fffffff, a CBOR.Exception is thrown.
ReturnsDescription
intDecoded integer.

2.1.1.6.  get_uint32()

Syntaxget_uint32()
DescriptionGet CBOR uint32 object.
If the return value is outside the range 0 to 0xffffffff, a CBOR.Exception is thrown.
ReturnsDescription
intDecoded integer.

2.1.1.7.  get_int53()

Syntaxget_int53()
DescriptionGet CBOR int53 object.
If the return value is outside the range Number.MIN_SAFE_INTEGER (-9007199254740991) to Number.MAX_SAFE_INTEGER (9007199254740991), a CBOR.Exception is thrown.
Since 53-bit integers are specific to JavaScript, int53 objects should be used with caution in cross-platform scenarios.
ReturnsDescription
intDecoded integer.

2.1.1.8.  get_int64()

Syntaxget_int64()
DescriptionGet CBOR int64 object.
If the return value is outside the range -0x8000000000000000 to 0x7fffffffffffffff, a CBOR.Exception is thrown.
ReturnsDescription
intDecoded integer.

2.1.1.9.  get_uint64()

Syntaxget_uint64()
DescriptionGet CBOR uint64 object.
If the return value is outside the range 0 to 0xffffffffffffffff, a CBOR.Exception is thrown.
ReturnsDescription
intDecoded integer.

2.1.1.10.  get_int128()

Syntaxget_int128()
DescriptionGet CBOR int128 object.
If the return value is outside the range -0x80000000000000000000000000000000 to 0x7fffffffffffffffffffffffffffffff, a CBOR.Exception is thrown.
ReturnsDescription
intDecoded integer.

2.1.1.11.  get_uint128()

Syntaxget_uint128()
DescriptionGet CBOR uint128 object.
If the return value is outside the range 0 to 0xffffffffffffffffffffffffffffffff, a CBOR.Exception is thrown.
ReturnsDescription
intDecoded integer.

2.1.1.12.  get_big_int()

Syntaxget_big_int()
DescriptionGet CBOR integer of any size.
See also Integer Numbers.
ReturnsDescription
intDecoded integer.

2.1.1.13.  CBOR.Int.create_int8()

SyntaxCBOR.Int.create_int8(value)
DescriptionCreate CBOR int8 object.
If value is outside the range -0x80 to 0x7f, a CBOR.Exception is thrown.
See also get_int8().
ParameterTypeDescription
valueintInteger to be wrapped.
ReturnsDescription
CBOR.IntInstantiated CBOR.Int object.

2.1.1.14.  CBOR.Int.create_uint8()

SyntaxCBOR.Int.create_uint8(value)
DescriptionCreate CBOR uint8 object.
If value is outside the range 0 to 0xff, a CBOR.Exception is thrown.
See also get_uint8().
ParameterTypeDescription
valueintInteger to be wrapped.
ReturnsDescription
CBOR.IntInstantiated CBOR.Int object.

2.1.1.15.  CBOR.Int.create_int16()

SyntaxCBOR.Int.create_int16(value)
DescriptionCreate CBOR int16 object.
If value is outside the range -0x8000 to 0x7fff, a CBOR.Exception is thrown.
See also get_int16().
ParameterTypeDescription
valueintInteger to be wrapped.
ReturnsDescription
CBOR.IntInstantiated CBOR.Int object.

2.1.1.16.  CBOR.Int.create_uint16()

SyntaxCBOR.Int.create_uint16(value)
DescriptionCreate CBOR uint16 object.
If value is outside the range 0 to 0xffff, a CBOR.Exception is thrown.
See also get_uint16().
ParameterTypeDescription
valueintInteger to be wrapped.
ReturnsDescription
CBOR.IntInstantiated CBOR.Int object.

2.1.1.17.  CBOR.Int.create_int32()

SyntaxCBOR.Int.create_int32(value)
DescriptionCreate CBOR int32 object.
If value is outside the range -0x80000000 to 0x7fffffff, a CBOR.Exception is thrown.
See also get_int32().
ParameterTypeDescription
valueintInteger to be wrapped.
ReturnsDescription
CBOR.IntInstantiated CBOR.Int object.

2.1.1.18.  CBOR.Int.create_uint32()

SyntaxCBOR.Int.create_uint32(value)
DescriptionCreate CBOR uint32 object.
If value is outside the range 0 to 0xffffffff, a CBOR.Exception is thrown.
See also get_uint32().
ParameterTypeDescription
valueintInteger to be wrapped.
ReturnsDescription
CBOR.IntInstantiated CBOR.Int object.

2.1.1.19.  CBOR.Int.create_int53()

SyntaxCBOR.Int.create_int53(value)
DescriptionCreate CBOR int53 object.
If value is outside the range Number.MIN_SAFE_INTEGER (-9007199254740991) to Number.MAX_SAFE_INTEGER (9007199254740991), a CBOR.Exception is thrown.
See also get_int53().
Since 53-bit integers are specific to JavaScript, int53 objects should be used with caution in cross-platform scenarios.
ParameterTypeDescription
valueintInteger to be wrapped.
ReturnsDescription
CBOR.IntInstantiated CBOR.Int object.

2.1.1.20.  CBOR.Int.create_int64()

SyntaxCBOR.Int.create_int64(value)
DescriptionCreate CBOR int64 object.
If value is outside the range -0x8000000000000000 to 0x7fffffffffffffff, a CBOR.Exception is thrown.
See also get_int64().
ParameterTypeDescription
valueintInteger to be wrapped.
ReturnsDescription
CBOR.IntInstantiated CBOR.Int object.

2.1.1.21.  CBOR.Int.create_uint64()

SyntaxCBOR.Int.create_uint64(value)
DescriptionCreate CBOR uint64 object.
If value is outside the range 0 to 0xffffffffffffffff, a CBOR.Exception is thrown.
See also get_uint64().
ParameterTypeDescription
valueintInteger to be wrapped.
ReturnsDescription
CBOR.IntInstantiated CBOR.Int object.

2.1.1.22.  CBOR.Int.create_int128()

SyntaxCBOR.Int.create_int128(value)
DescriptionCreate CBOR int128 object.
If value is outside the range -0x80000000000000000000000000000000 to 0x7fffffffffffffffffffffffffffffff, a CBOR.Exception is thrown.
See also get_int128().
ParameterTypeDescription
valueintInteger to be wrapped.
ReturnsDescription
CBOR.IntInstantiated CBOR.Int object.

2.1.1.23.  CBOR.Int.create_uint128()

SyntaxCBOR.Int.create_uint128(value)
DescriptionCreate CBOR uint128 object.
If value is outside the range 0 to 0xffffffffffffffffffffffffffffffff, a CBOR.Exception is thrown.
See also get_uint128().
ParameterTypeDescription
valueintInteger to be wrapped.
ReturnsDescription
CBOR.IntInstantiated CBOR.Int object.

2.2.  CBOR.Float

SyntaxCBOR.Float(value)
DescriptionConstructor. Creates a CBOR float object.
For supporting NaN and Infinity, see Non-Finite Numbers.
ParameterTypeDescription
valuefloatFloating-point number to be wrapped.
ReturnsDescription
CBOR.FloatObject.

2.2.1.  CBOR.Float Methods

2.2.1.1.  get_float16()

Syntaxget_float16()
DescriptionGet CBOR floating-point object.
If the CBOR object is not a float16 object, a CBOR.Exception is thrown.
ReturnsDescription
floatDecoded floating-point number.

2.2.1.2.  get_float32()

Syntaxget_float32()
DescriptionGet CBOR floating-point object.
If the CBOR object is not a float32 or float16 object, a CBOR.Exception is thrown.
ReturnsDescription
floatDecoded floating-point number.

2.2.1.3.  get_float64()

Syntaxget_float64()
DescriptionGet CBOR floating-point object.
If the CBOR object is not a float64, float32, or float16 object, a CBOR.Exception is thrown.
ReturnsDescription
floatDecoded floating-point number.

2.2.1.4.  CBOR.Float.create_extended_float()

SyntaxCBOR.Float.create_extended_float(value)
DescriptionCreates a CBOR float object.
Unlike CBOR.Float(), this method also supports the specific non-finite values, math.nan, math.inf, and ‑math.inf.
ParameterTypeDescription
valuefloatFloating-point number to be wrapped.
ReturnsDescription
CBOR.WrapperInstantiated CBOR.Float or CBOR.NonFinite object.

2.2.1.5.  get_extended_float64()

Syntaxget_extended_float64()
DescriptionGet CBOR floating-point object.
If the CBOR object is not a float64, float32, or float16 object, a CBOR.Exception is thrown.
Note that this method makes it transparent for applications if the returned value is a "regular" float, or one of the non-finite values, math.nan, math.inf, or ‑math.inf.
ReturnsDescription
floatDecoded floating-point number.

2.2.1.6.  CBOR.Float.create_float16()

SyntaxCBOR.Float.create_float16(value, exact)
DescriptionCreates a CBOR.Float object, where the value is converted to fit CBOR float16 representation.
If value (after applying IEEE 754 conversion rules), is out of range, or is non-finite, a CBOR.Exception is thrown.
If the exact flag is set, the conversion must be loss-less, else a CBOR.Exception is thrown.
See also get_float16().
ParameterTypeDescription
valuefloatFloating-point number to be wrapped.
exactboolIf true the conversion must be loss-less.
ReturnsDescription
CBOR.FloatInstantiated CBOR.Float object.

2.2.1.7.  CBOR.Float.create_float32()

SyntaxCBOR.Float.create_float32(value, exact)
DescriptionCreates a CBOR.Float object, where the value is converted to fit CBOR float32 representation.
If value (after applying IEEE 754 conversion rules), is out of range, or is non-finite, a CBOR.Exception is thrown.
If the exact flag is set, the conversion must be loss-less, else a CBOR.Exception is thrown.
Note that this method returns a float16 compatible object If value and precision is equivalent to the float32 representation (e.g. 2.5).
See also get_float32().
ParameterTypeDescription
valuefloatFloating-point number to be wrapped.
exactboolIf true the conversion must be loss-less.
ReturnsDescription
CBOR.FloatInstantiated CBOR.Float object.

2.2.2.  CBOR.Float Properties

2.2.2.1.  length

NameTypeDescription
lengthintLength in bytes of the underlying IEEE 754 type.

2.3.  CBOR.NonFinite

SyntaxCBOR.NonFinite(value)
DescriptionConstructor. Creates a CBOR non-finite float object.
The argument must be a valid 16, 32, or 64-bit non-finite number in IEEE 754 encoding.
ParameterTypeDescription
valueintNon-finite floating-point number to be wrapped.
ReturnsDescription
CBOR.NonFiniteObject.

2.3.1.  CBOR.NonFinite Methods

2.3.1.1.  get_non_finite()

Syntaxget_non_finite()
DescriptionGet actual non-finite object (value).
This method returns the value of a non-finite object. The value is provided in the most compact form based on CBOR serialization rules.
ReturnsDescription
intDecoded non-finite number as a BigInt.

2.3.1.2.  get_non_finite64()

Syntaxget_non_finite64()
DescriptionGet expanded non-finite object (value).
This method returns the value of a non-finite object after it has been expanded to 64 bits. That is, a received 7c01 will be returned as 7ff0040000000000.
ReturnsDescription
intDecoded non-finite number as a BigInt.

2.3.1.3.  is_nan()

Syntaxis_nan()
DescriptionCheck if non-finite object is a NaN.
This method returns True for all conformant NaN variants, else False is returned.
ReturnsDescription
boolResult.

2.3.1.4.  is_simple()

Syntaxis_simple()
DescriptionCheck if non-finite object is simple.
This method returns True if the non-finite object is a math.nan, math.inf, or &‑math.inf, else False is returned.
ReturnsDescription
boolResult.

2.3.1.5.  get_sign()

Syntaxget_sign()
DescriptionGet sign bit of non-finite object.
This method returns True if the sign bit is 1, else False is returned.
See also set_sign().
ReturnsDescription
boolResult.

2.3.1.6.  set_sign()

Syntaxset_sign(sign)
DescriptionSet sign bit of non-finite object.
The sign bit is expressed as a boolean. True = 1, False = 0.
See also get_sign().
ParameterTypeDescription
signboolSign bit.
ReturnsDescription
selfCurrent object.

2.3.1.7.  CBOR.NonFinite.create_payload()

SyntaxCBOR.NonFinite.create_payload(payload)
DescriptionCreates a payload object.
If payload is outside the range 0 to 0x1fffffffffffff, a CBOR.Exception is thrown.
For details turn to the Payload Option.
ParameterTypeDescription
payloadintPayload data.
ReturnsDescription
CBOR.NonFiniteInstantiated CBOR.NonFinite object.

2.3.1.8.  get_payload()

Syntaxget_payload()
Description Get payload data.
This method is the "consumer" counterpart to CBOR.NonFinite.create_payload().
ReturnsDescription
intPayload.

2.3.2.  CBOR.NonFinite Properties

2.3.2.1.  length

NameTypeDescription
lengthintLength in bytes of the underlying IEEE 754 type.

2.4.  CBOR.String

SyntaxCBOR.String(text_string)
DescriptionConstructor. Creates a CBOR text-string (tstr) object.
ParameterTypeDescription
text_stringstrString to be wrapped.
ReturnsDescription
CBOR.StringObject.

2.4.1.  CBOR.String Methods

2.4.1.1.  get_string()

Syntaxget_string()
DescriptionGet CBOR text-string.
ReturnsDescription
strDecoded text-string.

2.5.  CBOR.Bytes

SyntaxCBOR.Bytes(byte_string)
DescriptionConstructor. Creates a CBOR byte-string (bstr) object.
ParameterTypeDescription
byte_stringbytesBinary data to be wrapped.
ReturnsDescription
CBOR.BytesObject.

2.5.1.  CBOR.Bytes Methods

2.5.1.1.  get_bytes()

Syntaxget_bytes()
DescriptionGet CBOR byte-string.
ReturnsDescription
bytesDecoded byte-string.

2.6.  CBOR.Boolean

SyntaxCBOR.Boolean(value)
DescriptionConstructor. Creates a CBOR boolean (bool) object.
ParameterTypeDescription
valueboolBoolean to be wrapped.
ReturnsDescription
CBOR.BooleanObject.

2.6.1.  CBOR.Boolean Methods

2.6.1.1.  get_boolean()

Syntaxget_boolean()
DescriptionGet CBOR bool object.
ReturnsDescription
boolDecoded boolean.

2.7.  CBOR.Null

SyntaxCBOR.Null()
DescriptionConstructor. Creates a CBOR null object. See also is_null().
ReturnsDescription
CBOR.NullObject.

2.8.  CBOR.Array

SyntaxCBOR.Array()
DescriptionConstructor. Creates an empty CBOR array object.
ReturnsDescription
CBOR.ArrayObject.

2.8.1.  CBOR.Array Methods

2.8.1.1.  add()

Syntaxadd(object)
DescriptionAdd CBOR object to the array.
ParameterTypeDescription
objectCBOR.WrapperObject to be appended to the array.
ReturnsDescription
selfCurrent object.

2.8.1.2.  get()

Syntaxget(index)
DescriptionGet CBOR object at a specific position in the array.
ParameterTypeDescription
indexintArray index (0..length-1).
ReturnsDescription
CBOR.WrapperRetrieved object.

2.8.1.3.  remove()

Syntaxremove(index)
DescriptionRemove CBOR object at a specific position in the array.
ParameterTypeDescription
indexintArray index (0..length-1).
ReturnsDescription
CBOR.WrapperPrevious object.

2.8.1.4.  update()

Syntaxupdate(index, object)
DescriptionUpdate CBOR object at a specific position in the array.
ParameterTypeDescription
indexintArray index (0..length-1).
objectCBOR.WrapperUpdate object.
ReturnsDescription
CBOR.WrapperPrevious object.

2.8.1.5.  insert()

Syntaxinsert(index, object)
DescriptionInsert CBOR object before an object at a specific position in the array.
ParameterTypeDescription
indexintArray index (0..length).
If index is equal to length, object is appended.
objectCBOR.WrapperUpdate object.
ReturnsDescription
selfCurrent object.

2.8.1.6.  to_array()

Syntaxto_array()
DescriptionCopy array.
ReturnsDescription
[CBOR.Wrapper...]Array holding a copy of current CBOR.Wrapper objects.

2.8.1.7.  encode_as_sequence()

Syntaxencode_as_sequence()
DescriptionReturn the objects in the array as a CBOR sequence using Deterministic Encoding.
ReturnsDescription
bytesCBOR encoded data.

2.8.2.  CBOR.Array Properties

2.8.2.1.  length

NameTypeDescription
lengthintNumber of objects in the array.

2.9.  CBOR.Map

SyntaxCBOR.Map()
DescriptionConstructor. Creates an empty CBOR map object.
ReturnsDescription
CBOR.MapObject.

2.9.1.  CBOR.Map Methods

2.9.1.1.  set()

Syntaxset(key, object)
DescriptionSet map entry. If key is already defined, a CBOR.Exception is thrown.
Note: key order is of no importance since Deterministic Encoding performs the required map sorting automatically. See also set_sorting_mode().
Note: this implementation presumes that key objects are immutable. That is, the following code will throw a CBOR.Exception:
key = CBOR.Array()
map = CBOR.Map().set(key, CBOR.Int(5))
key.add(CBOR.String("data")) # Mutating key object
By defining key objects inline (chaining) or by preset variable declarations, key objects of any complexity can be used.
ParameterTypeDescription
keyCBOR.WrapperKey (name).
objectCBOR.WrapperObject (value).
ReturnsDescription
selfCurrent object.

2.9.1.2.  get()

Syntaxget(key)
DescriptionGet map entry. If key is undefined, a CBOR.Exception is thrown.
ParameterTypeDescription
keyCBOR.WrapperKey (name).
ReturnsDescription
CBOR.WrapperRetrieved object.

2.9.1.3.  get_conditionally()

Syntaxget_conditionally(key, default_object)
DescriptionGet map entry conditionally.
ParameterTypeDescription
keyCBOR.WrapperKey (name).
default_objectCBOR.WrapperObject to return if key is undefined.
Note: default_object may be None.
ReturnsDescription
CBOR.WrapperRetrieved or default object.

2.9.1.4.  contains_key()

Syntaxcontains_key(key)
DescriptionCheck map for key presence.
ParameterTypeDescription
keyCBOR.WrapperKey (name).
ReturnsDescription
boolTrue or False.

2.9.1.5.  remove()

Syntaxremove(key)
DescriptionRemove map entry. If key is undefined, a CBOR.Exception is thrown.
ParameterTypeDescription
keyCBOR.WrapperKey (name).
ReturnsDescription
CBOR.WrapperRemoved object (value).

2.9.1.6.  set_dynamic()

Syntaxset_dynamic(function)
DescriptionSet map entries using an external function while maintaining chaining of set-operations.
The function will be called with a single paramater holding the current object (map instance). The function must return the current object.
Consult test file dynamic.py for examples.
ParameterTypeDescription
functionfunction_refParameter holding a reference (pointer) to the function.
ReturnsDescription
selfCurrent object.

2.9.1.7.  merge()

Syntaxmerge(map)
DescriptionMerge maps. Performs a set() operation for each member of the map argument.
ParameterTypeDescription
mapCBOR.MapCBOR map wrapper object.
ReturnsDescription
selfCurrent object.

2.9.1.8.  update()

Syntaxupdate(key, object, existing)
DescriptionUpdate map entry.
ParameterTypeDescription
keyCBOR.WrapperKey (name).
objectCBOR.WrapperObject (value).
existingboolIf existing is True, key must be defined, else a CBOR.Exception is thrown.
If existing is False, a map entry will be created for key if not already defined.
ReturnsDescription
CBOR.WrapperPrevious object. May be None.

2.9.1.9.  get_keys()

Syntaxget_keys()
DescriptionGet map keys.
ReturnsDescription
[CBOR.Wrapper...]Array holding a copy of current key objects.

2.9.1.10.  set_sorting_mode()

Syntaxset_sorting_mode(pre_sorted_keys)
DescriptionSet the sorting mode of the CBOR.Map() object during set() operations.
Typical usage:
map = CBOR.Map().set_sorting_mode(True)
This method may be called multiple times which could be useful if you have a moderate set of unsorted meta data keys combined with a sorted large table-like set of keys. Note that this method has no effect on decoding operations.
ParameterTypeDescription
pre_sorted_keysboolIf True, keys must be provided in (CBOR wise) ascending order which can improve performance for maps having a huge number of keys. Improper key order causes a CBOR.Exception to be thrown. By default, map keys are sorted internally.
ReturnsDescription
selfCurrent object.

2.9.2.  CBOR.Map Properties

2.9.2.1.  length

NameTypeDescription
lengthintNumber of map entries.

2.10.  CBOR.Tag

SyntaxCBOR.Tag(tag_number, object)
DescriptionConstructor. Creates a CBOR tag object.
The CBOR tag constructor accepts any valid parameters but performs thorough syntax checks on tag 0 (CBOR date/time), tag 1 (CBOR epoch time), and tag 1010 [COTXlink].
ParameterTypeDescription
tag_numberintTag number.
objectCBOR.WrapperObject to be wrapped in a tag.
ReturnsDescription
CBOR.TagObject.

2.10.1.  CBOR.Tag Methods

2.10.1.1.  get()

Syntaxget()
DescriptionGet tagged CBOR object.
ReturnsDescription
CBOR.WrapperRetrieved object.

2.10.1.2.  get_tag_number()

Syntaxget_tag_number()
DescriptionGet CBOR tag number.
ReturnsDescription
intDecoded tag number.

2.10.1.3.  CBOR.Tag.create_cotx_tag()

SyntaxCBOR.Tag.create_cotx_tag(id, object)
DescriptionConveniance method for creating a [COTXlink] compatible tag.
See also cotx_id and cotx_object.
ParameterTypeDescription
idstrURL or other suitable identfier.
objectCBOR.WrapperTagged object.
ReturnsDescription
CBOR.TagWrapper holding a COTX object.

2.10.2.  CBOR.Tag Properties

2.10.2.1.  cotx_id

NameTypeDescription
cotx_idstrCOTX [COTXlink] support: object ID string.
Only valid for COTX tags. See also CBOR.Tag.create_cotx_tag().

2.10.2.2.  cotx_object

NameTypeDescription
cotx_objectCBOR.WrapperCOTX [COTXlink] support: wrapped object.
Only valid for COTX tags. See also CBOR.Tag.create_cotx_tag().

2.11.  CBOR.Simple

SyntaxCBOR.Simple(value)
DescriptionConstructor. Creates a CBOR simple object.
If value is outside the range 0-23 and 32-255, a CBOR.Exception is thrown.
A primary use case for simple types in the range of 0-19 and 32-255, is serving as a limited set of unique and reserved labels (keys) in CBOR maps.
ParameterTypeDescription
valueintSimple value.
ReturnsDescription
CBOR.SimpleObject.

2.11.1.  CBOR.Simple Methods

2.11.1.1.  get_simple()

Syntaxget_simple()
DescriptionGet CBOR simple object.
ReturnsDescription
intReturned simple value.

3.  Time Objects

Since CBOR lacks dedicated (native) time-objects, section 3.4.1 and 3.4.2 of CBOR [RFC8949link] define tag 0 and 1 for this purpose. CBOR.py provides built-in decoders for these tags (CBOR.Tag). That is, if the current object is a tag 0, it is sufficient calling get_date_time(). Note that these methods are also available without the tag construct.

3.1.  get_date_time()

Syntaxget_date_time()
DescriptionGet DateTime object.
This method performs a get_string(). The returned string is subsequently used for initiating a Python datetime object.
If not all of the following conditions are met, a CBOR.Exception is thrown:
  • The underlying object is a CBOR.String.
  • The string matches the ISO date/time format described in section 5.6 of [RFC3339link].
  • The optional sub-second field (.nnn) features less than ten digits.
  • The date/time object is within the range "0000-01-01T00:00:00Z" to "9999-12-31T23:59:59Z".
ReturnsDescription
datetimeDate object

3.2.  get_epoch_time()

Syntaxget_epoch_time()
DescriptionGet EpochTime object.
Depending on the type of the current object, this method performs a get_int53() or a get_float64(). The returned number is subsequently used for initiating a Python datetime object.
If not all of the following conditions are met, a CBOR.Exception is thrown:
  • The underlying object is a CBOR.Int or CBOR.Float.
  • The Epoch [TIMElink] object is within the range 0 ("1970-01-01T00:00:00Z") to 253402300799 ("9999-12-31T23:59:59Z").
ReturnsDescription
datetimeDate object

4.  Common Wrapper Methods

The CBOR wrapper objects support a set of common methods, described in this sub-section.

4.1.  encode()

Syntaxencode()
DescriptionEncode (aka "serialize") self.
Note: this method always return CBOR data using Deterministic Encoding.
ReturnsDescription
bytesCBOR encoded data.

4.2.  clone()

Syntaxclone()
DescriptionCreate a new instance of self, initialized with the original CBOR content.
ReturnsDescription
CBOR.WrapperDeep copy of self.

4.3.  equals()

Syntaxequals(object)
DescriptionCompare self with another CBOR object.
The result is True if and only if object is not None and is a CBOR.Wrapper, and the associated binary encodings (as provided by encode()) are equivalent.
Note that equals() is equivalent to the Python '==' operator.
ParameterTypeDescription
objectCBOR.WrapperArgument to compare with.
ReturnsDescription
boolReturns True if self is equal to object, else False is returned.

4.4.  to_diagnostic()

Syntaxto_diagnostic(pretty_print)
DescriptionRender self in Diagnostic Notation. In similarity to encode(), this method always produce data in Deterministic Encoding, irrespective to how the data was created. See also to_string().
If self (as well as possible child objects), conforms to the subset of data types supported by JSON, this method can also be used to generate JSON data.
ParameterTypeDescription
pretty_printboolIf pretty_print is True, additional white space is inserted between individual objects in maps and arrays, to make the result easier to read.
ReturnsDescription
strTextual version of the wrapped CBOR content.

4.5.  to_string()

Syntaxto_string()
DescriptionRender self in Diagnostic Notation. Equivalent to calling to_diagnostic() with a True argument.
The Python str(object) function is equivalent to object.to_string().
ReturnsDescription
strTextual version of the wrapped CBOR content.

4.6.  is_null()

Syntaxis_null()
DescriptionCheck for CBOR null.
Note: if check_for_unread() is used, self will only be regarded as "read" if it actually is a CBOR null item.
See also CBOR.Null().
ReturnsDescription
boolReturns True if self holds a CBOR null item, else False is returned.

4.7.  check_for_unread()

Syntaxcheck_for_unread()
Description Check if self including possible child objects has been read (like calling get_int32()). If not all of the associated objects have been read, a CBOR.Exception is thrown.
The purpose of this method is to detect possible misunderstandings between parties using CBOR based protocols. Together with the strict type checking performed by the CBOR.py API, a programmatic counterpart to schema-based decoding can be achieved.
Note that array get(), map get(), and tag get() only locate objects, and thus do not count as "read".
To cope with elements that are redundant, scan() can be used:
array = CBOR.from_diagnostic("[3, {}]")
operation = array.get(0).get_int8()
array.get(1).scan()    # mark array[1] as read
array.check_for_unread()
ReturnsDescription
selfCurrent object.

4.8.  scan()

Syntaxscan()
DescriptionScan self as well as possible child objects in order to make them appear as "read". This is only meaningful in conjunction with check_for_unread().
ReturnsDescription
selfCurrent object.

5.  Decoding CBOR

CBOR decoding comes in two flavors, binary and Diagnostic Notation. Both decoders return the result as CBOR wrapper objects. This section lists the decoder methods. See also encode().

5.1.  CBOR.decode()

SyntaxCBOR.decode(cbor)
DescriptionDecode (aka "deserialize") CBOR object.
This method is equivalent to:
import io

CBOR.init_decoder(io.BytesIO(cbor), 0,
    len(cbor)).decode_with_options()
Unsupported or malformed CBOR data cause a CBOR.Exception to be thrown.
ParameterTypeDescription
cborbytesCBOR binary data holding exactly one CBOR object.
ReturnsDescription
CBOR.WrapperObject.

5.2.  CBOR.init_decoder()

SyntaxCBOR.init_decoder(cbor_stream, options, max_length)
DescriptionCreate a customized CBOR decoder. This decoding method presumes that the actual decoding is performed by one or more (for sequences only) calls to Decoder.decode_with_options().
Note that irrespective of options, the decoder maintains parsed data in the form required for Deterministic Encoding.
ParameterTypeDescription
cbor_streamio.BufferedIOBaseCBOR data supplied as a byte stream.
optionsintThe decoder options. Multiple options can be combined using the binary OR-operator ("|"). A zero (0) sets the decoder default mode. The options are defined by the following constants:
CBOR.SEQUENCE_MODE:
If the CBOR.SEQUENCE_MODE option is defined, the following apply:
  • The decoder returns after having decoded a single CBOR object, while preparing for the next object.
  • If no data is found (EOF), None is returned (empty sequences are permitted).
Note that data that has not yet been decoded, is not verified for correctness. The application note Large Payloads shows how this can be utilized.
CBOR.LENIENT_MAP_DECODING:
By default, the decoder requires that CBOR maps conform to the Deterministic Encoding rules.
The CBOR.LENIENT_MAP_DECODING option makes the decoder accept CBOR maps with arbitrary key ordering. Note that duplicate keys still cause a CBOR.Exception to be thrown.
CBOR.LENIENT_NUMBER_DECODING:
By default, the decoder requires that CBOR numbers conform to the Deterministic Encoding rules.
The CBOR.LENIENT_NUMBER_DECODING option makes the decoder accept different representations of CBOR int/bigint and float objects, only limited by [RFC8949link].
max_lengthintThe maximum number of bytes accepted.
ReturnsDescription
DecoderDecoder object to be used with Decoder.decode_with_options().

5.3.  Decoder.set_max_nesting_level()

SyntaxDecoder.set_max_nesting_level(max_level)
DescriptionSet max structure nesting level.
Structure refers to CBOR tags, arrays, and maps. Example: [{}] represents a nesting level of 2. Usage in code:
CBOR.init_decoder(cbor_stream, options, max_length)  \
  .set_max_nesting_level(20)  \
  .decode_with_options()
ParameterTypeDescription
max_levelintMaximum nesting level. The default setting is 100.
ReturnsDescription
DecoderDecoder object to be used with Decoder.decode_with_options().

5.4.  Decoder.decode_with_options()

SyntaxDecoder.decode_with_options()
DescriptionDecode CBOR data with options.
Unsupported or malformed CBOR data cause a CBOR.Exception to be thrown.
ReturnsDescription
CBOR.WrapperObject or None (for EOF sequences only).

5.5.  Decoder.get_byte_count()

SyntaxDecoder.get_byte_count()
DescriptionGet decoder byte count.
This is equivalent to the position of the next item to be read.
ReturnsDescription
intThe number of bytes read so far.

5.6.  CBOR.from_diagnostic()

SyntaxCBOR.from_diagnostic(cbor_text)
DescriptionDecode a CBOR object provided in Diagnostic Notation. See also CBOR.from_diagnostic_seq().
This method always returns CBOR data using Deterministic Encoding.
This method can also be used for decoding JSON data.
ParameterTypeDescription
cbor_textstrCBOR in textual format.
ReturnsDescription
CBOR.WrapperObject.

5.7.  CBOR.from_diagnostic_seq()

SyntaxCBOR.from_diagnostic_seq(cbor_text)
DescriptionDecode CBOR objects provided in Diagnostic Notation. Unlike CBOR.from_diagnostic(), this method also accepts CBOR sequences, using a comma character (',') as a separator.
Note: empty sequences are permitted.
ParameterTypeDescription
cbor_textstrCBOR in textual format.
ReturnsDescription
[CBOR.Wrapper...]Array holding zero or more objects.

6.  Utility Methods

The CBOR.py implementation supports a set of utility methods.

6.1.  CBOR.create_date_time()

SyntaxCBOR.create_date_time(instant, millis, utc)
DescriptionCreate DateTime object.
This method creates a date/time string in the ISO format described in section 5.6 of [RFC3339link]. The string is subsequently wrapped in a CBOR.String object.
If instant is outside the range "0000-01-01T00:00:00Z" to "9999-12-31T23:59:59Z", a CBOR.Exception is thrown.
If millis is True the date/time string will feature milliseconds (.nnn) as well.
Sample code:
from datetime import datetime

date_time = CBOR.create_date_time(
    datetime.now(), True, False)
print(date_time.to_string())  # Diagnostic notation
"2026-02-05T13:55:42.418+01:00"
See also get_date_time().
ParameterTypeDescription
instantdatetimeTime source object.
millisboolIf millis is True, the milliseconds of the instant object will be featured in the created time object. Note: if the millisecond part of the instant object is zero, millis is considered to be False.
If millis is False, the millisecond part of the instant object will not be used, but may after rounding, add a second to the created time object.
utcboolIf utc is True, the UTC time zone (denoted by a terminating Z) will be used, else the local time followed by the UTC offset (±hh:mm) will be used.
ReturnsDescription
CBOR.StringWrapper holding a DateTime object.

6.2.  CBOR.create_epoch_time()

SyntaxCBOR.create_epoch_time(instant, millis)
DescriptionCreate EpochTime object.
This method creates an Epoch [TIMElink] time stamp.
If instant is outside the range 0 ("1970-01-01T00:00:00Z") to 253402300799 ("9999-12-31T23:59:59Z"), a CBOR.Exception is thrown.
If millis is True a CBOR.Float object holding seconds with a milliseconds fraction will be created, else a CBOR.Int object holding seconds will be created.
Sample code:
from datetime import datetime

epoch = CBOR.create_epoch_time(datetime.now(), False)
print(epoch.to_string())  # Diagnostic notation
1764939916
See also get_epoch_time().
ParameterTypeDescription
instantdatetimeTime source object.
millisboolIf millis is True, the milliseconds of the instant object will be featured in the created time object. Note: if the millisecond part of the instant object is zero, millis is considered to be False.
If millis is False, the millisecond part of the instant object will not be used, but may after rounding, add a second to the created time object.
ReturnsDescription
CBOR.WrapperWrapper holding an EpochTime object.

7.  CBOR Numbers

7.1.  Integers

The following table holds additional CDDL defintions [CDDL-EXTlink] and their API counterparts:
CDDLDecodingEncodingConstructorNotes
int8 get_int8() CBOR.Int.create_int8(value) CBOR.Int(value) 1, 2
uint8 get_uint8() CBOR.Int.create_uint8(value) CBOR.Int(value) 1, 2
int16 get_int16() CBOR.Int.create_int16(value) CBOR.Int(value) 1, 2
uint16 get_uint16() CBOR.Int.create_uint16(value) CBOR.Int(value) 1, 2
int32 get_int32() CBOR.Int.create_int32(value) CBOR.Int(value) 1, 2
uint32 get_uint32() CBOR.Int.create_uint32(value) CBOR.Int(value) 1, 2
int53 get_int53() CBOR.Int.create_int53(value) CBOR.Int(value) 1, 3
int64 get_int64() CBOR.Int.create_int64(value) CBOR.Int(value) 1, 2
uint64 get_uint64() CBOR.Int.create_uint64(value) CBOR.Int(value) 1, 2
int128 get_int128() CBOR.Int.create_int128(value) CBOR.Int(value) 1, 2
uint128 get_uint128() CBOR.Int.create_uint128(value) CBOR.Int(value) 1, 2
integer get_big_int() N/A - Constructor Only CBOR.Int(value)
  1. The only difference between the "Encoding" method and the "Constructor", is that the former verifies that the input argument matches the permitted range as well. For a description of the valid range for a specific integer type, lookup the associated "Decoding" method.
  2. Counterparts to the fixed-size, two's complement integer types, featured in languages like Java, C, and Rust.
  3. Integer mapping the JavaScript Number type. Consult get_int53() for details.

7.2.  Floating-Point Numbers

Although CBOR encoding depends on 16, 32, and 64-bit IEEE 754 variants, the CBOR.py implementation makes this transparent. The CBOR.Float wrapper object only exposes the Python float type.

For applications depending on non-finite numbers (NaN and Infinity), turn to Non-Finite Numbers.

See also CBOR.Float.create_float16() and CBOR.Float.create_float32().

8.  Diagnostic Notation

Creating CBOR data in diagnostic (textual) notation is provided by the to_string() method.

However, through the CBOR.from_diagnostic() method, CBOR data may also be provided in diagnostic notation, making CBOR useful for local "config" and test data files as well.

Due to the Deterministic Encoding scheme used by CBOR.py, CBOR data can be bidirectionally converted between its native (binary) format and diagnostic notation without getting corrupted. Note though that text-binary-text "roundtrips" do not necessarily return identical text: 0x10 used as diagnostic notation input will return 16 as diagnostic notation output.

The following table shows how CBOR objects should be represented in diagnostic notation:
CDDLSyntaxCommentNotes
/ comment text / Multi-line comment. Multi-line comments are treated as whitespace and may thus also be used between CBOR objects. 6
# comment text Single-line comment. Single-line comments are terminated by a newline character ('\n') or EOF. Single-line comments may also terminate lines holding regular CBOR items. 6
integer {sign}{0b | 0o | 0x} n Arbitrary sized integers without fractional components or exponents.
For input data in diagnostic notation, binary, octal, and hexadecimal notation is also supported by prepending numbers with 0b, 0o, and 0x respectively. The latter also permit arbitrary insertions of '_' characters between digits to enable grouping of data like 0b100_000000001.
1, 2
float {sign}n.n{e±n} Floating point values must include a decimal point and an optional exponent. 1, 2
float'hex data' Any valid 16, 32, or 64-bit float value, including NaN with payloads like float'7ff0800000000001'.
NaN Not a number in the default encoding (f97e00).
{sign}Infinity Infinity. 2
bstr h'hex data' Byte data provided in hexadecimal notation. Each byte must be represented by two hexadecimal digits. 3
b64'base64 data' Byte data provided in base64 or base64URL notation. Padding with '=' characters is optional. 3, 6
'text' Byte data provided as UTF-8 encoded text. 4, 5, 6
<< object... >> Construct holding zero or more comma-separated CBOR objects that are subsequently wrapped in a byte string. 6
tstr "text" UTF-8 encoded text string. 4, 5
bool true | false Boolean value.
null null Null value.
[] [ object... ] Array with zero or more comma-separated CBOR objects.
{} { key:value... } Map with zero or more comma-separated key/value pairs. Key and value pairs are expressed as CBOR objects, separated by a ':' character.
#6.nnn n( object ) Tag holding a CBOR object. 1
#7.nnn simple(n) Simple value. 1
, Separator character for CBOR sequences.
  1. The letter n in the Syntax column denotes one or more digits.
  2. The optional {sign} must be a single hyphen ('-') character.
  3. Input only: between tokens, the whitespace characters ' ', '\t', '\r', and '\n', are ignored.
  4. Input only: inside of string quotes, the control character '\n' becomes a part of the text string. For nomalizing line terminators, a single '\r' or the combination '\r\n' are rewritten as '\n'. To avoid getting newline characters ('\n') included in multi-line text strings, a line continuation marker consisting of a backslash ('\') immediately preceding the newline may be used.
  5. Text strings may also include the JavaScript compatible escape sequences '\'', '\"', '\\', '\b', '\f', '\n', '\r', '\t', and '\uhhhh'.
  6. Input only.

9.  Deterministic Encoding

While there are different ways you can encode certain CBOR objects, this is non-trivial to support in general purpose platform-based tools, not to mention the limited utility of such measures. Therefore the CBOR.py API implements specific (non-variant) encodings, aka "Deterministic Encoding". Fortunately, the selected encoding scheme is backward compatible with most existing CBOR decoders. However, for decoding (only), compliance with deterministic encoding rules may be relaxed, enabling the processing of CBOR data created by applications using "legacy" encoding schemes as well.

The determinism scheme is described in [CBOR::Corelink].

10.  Using the CBOR API

This section provides a few examples on how to use the CBOR API. Note that the following declaration must be included at the top of each source file:
from org.webpki.cbor import CBOR

10.1.  Encode CBOR Data

The following code shows how you can create CBOR-encoded data:
cbor = CBOR.Map()  \
           .set(CBOR.Int(1), CBOR.Float(45.7))  \
           .set(CBOR.Int(2), CBOR.String("Hi there!")).encode()

print(cbor.hex())
a201fb4046d9999999999a0269486920746865726521

10.2.  Decode CBOR Data

The following code shows how you can decode CBOR-encoded data, here using the result of the previous encoding example:
map = CBOR.decode(cbor)  # Using the result from encoding

print(map.to_string())   # Diagnostic notation
{
  1: 45.7,
  2: "Hi there!"
}


print("Value=" + str(map.get(CBOR.Int(1)).get_float64()))
Value=45.7

10.3.  Decode Variant CBOR Data

The following code shows how you can decode variant CBOR-encoded data:
int_or_string = CBOR.decode(cbor)
if isinstance(int_or_string, CBOR.Int):
    i = int_or_string.get_int32()
    # Do something with i...
else:
    # Throws a CBOR.Exception if the object is not a CBOR.String
    s = int_or_string.get_string()
    # Do something with s...

10.4.  Decode CBOR Diagnostic Notation

The following code shows how you can decode CBOR provided in Diagnostic Notation:
cbor = CBOR.from_diagnostic("""{
# Comments are also permitted
  1: 45.7,
  2: "Hi there!"
}""").encode()

print(cbor.hex())
a201fb4046d9999999999a0269486920746865726521

10.5.  Encode CBOR Sequence

The following code shows how you can create CBOR sequences:
cbor = CBOR.Array()  \
    .add(CBOR.Map().set(CBOR.Int(7), CBOR.String("Hi!")))  \
    .add(CBOR.Float(4.5))  \
    .encode_as_sequence()

print(cbor.hex())
a10763486921f94480

10.6.  Decode CBOR Sequence

The following code shows how you can decode CBOR sequences, here using the result of the previous encoding example:
import io

decoder = CBOR.init_decoder(io.BytesIO(cbor), CBOR.SEQUENCE_MODE, 10000)
while object := decoder.decode_with_options():
    print('\n' + object.to_string())

{
  7: "Hi!"
}


4.5

11.  Error Handling

Encoding and decoding errors throw CBOR.Exception, derived from the Python Exception object.

12.  Version

API version: Beta 1.0.0. Note that the current API version is accessible through the static property CBOR.version.
Document version: 2026-03-13