Skip to content
This repository was archived by the owner on Apr 19, 2024. It is now read-only.

Commit a59b2ba

Browse files
committed
add methods to manage codec registry Codecs
1 parent ff82286 commit a59b2ba

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

multihash.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,51 @@ def reset(cls):
196196
except ImportError:
197197
pass
198198

199+
@classmethod
200+
def get_codecs(cls):
201+
"""Return a set of registered codec names.
202+
203+
>>> Codecs.reset()
204+
>>> 'base64' in Codecs.get_codecs()
205+
True
206+
"""
207+
return {codec for codec in cls._codecs}
208+
209+
@classmethod
210+
def register(cls, name, encode, decode):
211+
"""Add a codec to the registry.
212+
213+
Registers a codec with the given `name` (a string) to be used with the
214+
given `encode` and `decode` functions, which take a `bytes` object and
215+
return another one. Existing codecs are replaced.
216+
217+
>>> import binascii
218+
>>> Codecs.register('uu', binascii.b2a_uu, binascii.a2b_uu)
219+
>>> Codecs.get_decoder('uu') is binascii.a2b_uu
220+
True
221+
>>> Codecs.reset()
222+
>>> 'uu' in Codecs.get_codecs()
223+
False
224+
"""
225+
cls._codecs[name] = cls._codec(encode, decode)
226+
227+
@classmethod
228+
def unregister(cls, name):
229+
"""Remove a codec from the registry.
230+
231+
Unregisters the codec with the given `name` (a string). If the codec
232+
is not registered, a `KeyError` is raised.
233+
234+
>>> import binascii
235+
>>> Codecs.register('uu', binascii.b2a_uu, binascii.a2b_uu)
236+
>>> 'uu' in Codecs.get_codecs()
237+
True
238+
>>> Codecs.unregister('uu')
239+
>>> 'uu' in Codecs.get_codecs()
240+
False
241+
"""
242+
del cls._codecs[name]
243+
199244
@classmethod
200245
def get_encoder(cls, encoding):
201246
r"""Return an encoder for the given `encoding`.

0 commit comments

Comments
 (0)