cbor2 icon indicating copy to clipboard operation
cbor2 copied to clipboard

The encoder is difficult to customize

Open Changaco opened this issue 6 years ago • 1 comments

Right now the only simple way to avoid #37 is to modify a global variable (see code below), which could theoretically break another module that uses cbor2 in the same process and expects the encoding of date objects to work.

import cbor2
cbor2.encoder.default_encoders.pop(date)

It could be nice to have a CBOR class that would hold configuration variables and implement the dump, dumps, load and loads functions. That would make it possible to create a custom CBOR encoder/decoder that could be used exactly like the global cbor2.* functions but would encode/decode slightly differently. For example:

from datetime import date
from cbor2 import CBOR
dateless_cbor = CBOR()
dateless_cbor.encoders.pop(date, None)
dateless_cbor.dumps(date(2019, 2, 20))  # raises CBOREncodeError

Changaco avatar Feb 20 '19 16:02 Changaco

dumps is just a wrapper around the CBOREncoder object which has a private _encoders dictionary

Sekenre avatar Feb 21 '19 09:02 Sekenre