msgpack-python/msgpack/__init__.py

55 lines
1.4 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 01:12:57 +09:00
from collections import namedtuple
2013-10-21 00:59:22 +09:00
2013-10-21 01:12:57 +09:00
class ExtType(namedtuple('ExtType', 'code data')):
2013-10-21 01:47:54 +09:00
"""ExtType represents ext type in msgpack."""
2013-10-21 01:12:57 +09:00
def __new__(cls, code, data):
2013-10-21 00:59:22 +09:00
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")
2013-10-21 01:12:57 +09:00
return super(ExtType, cls).__new__(cls, code, data)
2013-10-21 00:59:22 +09:00
import os
if os.environ.get('MSGPACK_PUREPYTHON'):
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