__init__.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # coding: utf-8
  2. from msgpack._version import version
  3. from msgpack.exceptions import *
  4. from collections import namedtuple
  5. class ExtType(namedtuple('ExtType', 'code data')):
  6. """ExtType represents ext type in msgpack."""
  7. def __new__(cls, code, data):
  8. if not isinstance(code, int):
  9. raise TypeError("code must be int")
  10. if not isinstance(data, bytes):
  11. raise TypeError("data must be bytes")
  12. if not 0 <= code <= 127:
  13. raise ValueError("code must be 0~127")
  14. return super(ExtType, cls).__new__(cls, code, data)
  15. import os
  16. if os.environ.get('MSGPACK_PUREPYTHON'):
  17. from msgpack.fallback import Packer, unpack, unpackb, Unpacker
  18. else:
  19. try:
  20. from msgpack._packer import Packer
  21. from msgpack._unpacker import unpack, unpackb, Unpacker
  22. except ImportError:
  23. from msgpack.fallback import Packer, unpack, unpackb, Unpacker
  24. def pack(o, stream, **kwargs):
  25. """
  26. Pack object `o` and write it to `stream`
  27. See :class:`Packer` for options.
  28. """
  29. packer = Packer(**kwargs)
  30. stream.write(packer.pack(o))
  31. def packb(o, **kwargs):
  32. """
  33. Pack object `o` and return packed bytes
  34. See :class:`Packer` for options.
  35. """
  36. return Packer(**kwargs).pack(o)
  37. # alias for compatibility to simplejson/marshal/pickle.
  38. load = unpack
  39. loads = unpackb
  40. dump = pack
  41. dumps = packb