msgpack-python/msgpack/__init__.py

66 lines
1.6 KiB
Python
Raw Normal View History

# coding: utf-8
from msgpack._version import version
2012-12-11 22:05:00 +09:00
from msgpack.exceptions import *
2013-10-21 00:59:22 +09:00
class ExtType(object):
__slots__ = ('code', 'data')
def __init__(self, code, data):
if not isinstance(code, int):
raise TypeError("code must be int")
if not isinstance(data, bytes):
raise TypeError("data must be bytes")
if not 0 <= code <= 127:
raise ValueError("code must be 0~127")
self.code = code
self.data = data
def __eq__(self, other):
if not isinstance(other, ExtType):
return NotImplemented
return self.code == other.code and self.data == other.data
def __hash__(self):
return self.code ^ hash(self.data)
def __repr__(self):
return "msgpack.ExtType(%r, %r)" % (self.code, self.data)
import os
if os.environ.get('MSGPACK_PUREPYTHON'):
2013-10-17 08:44:25 +09:00
from msgpack.fallback import Packer, unpack, unpackb, Unpacker
else:
try:
2013-10-17 08:44:25 +09:00
from msgpack._packer import Packer
from msgpack._unpacker import unpack, unpackb, Unpacker
except ImportError:
from msgpack.fallback import Packer, unpack, unpackb, Unpacker
2013-10-17 08:44:25 +09:00
def pack(o, stream, **kwargs):
"""
Pack object `o` and write it to `stream`
See :class:`Packer` for options.
"""
packer = Packer(**kwargs)
stream.write(packer.pack(o))
2013-10-20 20:28:32 +09:00
2013-10-17 08:44:25 +09:00
def packb(o, **kwargs):
"""
Pack object `o` and return packed bytes
See :class:`Packer` for options.
"""
return Packer(**kwargs).pack(o)
# alias for compatibility to simplejson/marshal/pickle.
load = unpack
loads = unpackb
dump = pack
dumps = packb