Debian Codegraph @

README.md

raw
1 # MessagePack for Python
2
3 [![Build Status](https://github.com/msgpack/msgpack-python/actions/workflows/wheel.yml/badge.svg)](https://github.com/msgpack/msgpack-python/actions/workflows/wheel.yml)
4 [![Documentation Status](https://readthedocs.org/projects/msgpack-python/badge/?version=latest)](https://msgpack-python.readthedocs.io/en/latest/?badge=latest)
5
6 ## What is this?
7
8 [MessagePack](https://msgpack.org/) is an efficient binary serialization format.
9 It lets you exchange data among multiple languages like JSON.
10 But it's faster and smaller.
11 This package provides CPython bindings for reading and writing MessagePack data.
12
13 ## Install
14
15 ```
16 $ pip install msgpack
17 ```
18
19 ### Pure Python implementation
20
21 The extension module in msgpack (`msgpack._cmsgpack`) does not support PyPy.
22
23 But msgpack provides a pure Python implementation (`msgpack.fallback`) for PyPy.
24
25
26 ### Windows
27
28 If you can't use a binary distribution, you need to install Visual Studio
29 or the Windows SDK on Windows.
30 Without the extension, the pure Python implementation on CPython runs slowly.
31
32
33 ## How to use
34
35 ### One-shot pack & unpack
36
37 Use `packb` for packing and `unpackb` for unpacking.
38 msgpack provides `dumps` and `loads` as aliases for compatibility with
39 `json` and `pickle`.
40
41 `pack` and `dump` pack to a file-like object.
42 `unpack` and `load` unpack from a file-like object.
43
44 ```pycon
45 >>> import msgpack
46 >>> msgpack.packb([1, 2, 3])
47 '\x93\x01\x02\x03'
48 >>> msgpack.unpackb(_)
49 [1, 2, 3]
50 ```
51
52 Read the docstring for options.
53
54
55 ### Streaming unpacking
56
57 `Unpacker` is a "streaming unpacker". It unpacks multiple objects from one
58 stream (or from bytes provided through its `feed` method).
59
60 ```py
61 import msgpack
62 from io import BytesIO
63
64 buf = BytesIO()
65 for i in range(100):
66 buf.write(msgpack.packb(i))
67
68 buf.seek(0)
69
70 unpacker = msgpack.Unpacker(buf)
71 for unpacked in unpacker:
72 print(unpacked)
73 ```
74
75 > [!IMPORTANT]
76 > If `Unpacker.unpack()` stops with an exception other than `OutOfData`, that `Unpacker` cannot be reused.
77 > Create a new `Unpacker` when reading another stream.
78
79
80 ### Packing/unpacking of custom data types
81
82 It is also possible to pack/unpack custom data types. Here is an example for
83 `datetime.datetime`.
84
85 ```py
86 import datetime
87 import msgpack
88
89 useful_dict = {
90 "id": 1,
91 "created": datetime.datetime.now(),
92 }
93
94 def decode_datetime(obj):
95 if '__datetime__' in obj:
96 obj = datetime.datetime.strptime(obj["as_str"], "%Y%m%dT%H:%M:%S.%f")
97 return obj
98
99 def encode_datetime(obj):
100 if isinstance(obj, datetime.datetime):
101 return {'__datetime__': True, 'as_str': obj.strftime("%Y%m%dT%H:%M:%S.%f")}
102 return obj
103
104
105 packed_dict = msgpack.packb(useful_dict, default=encode_datetime)
106 this_dict_again = msgpack.unpackb(packed_dict, object_hook=decode_datetime)
107 ```
108
109 `Unpacker`'s `object_hook` callback receives a dict; the
110 `object_pairs_hook` callback may instead be used to receive a list of
111 key-value pairs.
112
113 NOTE: msgpack can encode datetime with tzinfo into standard ext type for now.
114 See `datetime` option in `Packer` docstring.
115
116
117 ### Extended types
118
119 It is also possible to pack/unpack custom data types using the **ext** type.
120
121 ```pycon
122 >>> import msgpack
123 >>> import array
124 >>> def default(obj):
125 ... if isinstance(obj, array.array) and obj.typecode == 'd':
126 ... return msgpack.ExtType(42, obj.tobytes())
127 ... raise TypeError("Unknown type: %r" % (obj,))
128 ...
129 >>> def ext_hook(code, data):
130 ... if code == 42:
131 ... a = array.array('d')
132 ... a.frombytes(data)
133 ... return a
134 ... return msgpack.ExtType(code, data)
135 ...
136 >>> data = array.array('d', [1.2, 3.4])
137 >>> packed = msgpack.packb(data, default=default)
138 >>> unpacked = msgpack.unpackb(packed, ext_hook=ext_hook)
139 >>> data == unpacked
140 True
141 ```
142
143
144 ### Advanced unpacking control
145
146 As an alternative to iteration, `Unpacker` objects provide `unpack`,
147 `skip`, `read_array_header`, and `read_map_header` methods. The former two
148 read an entire message from the stream, respectively deserializing and returning
149 the result, or ignoring it. The latter two methods return the number of elements
150 in the upcoming container, so that each element in an array, or key-value pair
151 in a map, can be unpacked or skipped individually.
152
153
154 ## Notes
155
156 ### String and binary types in the old MessagePack spec
157
158 Early versions of msgpack didn't distinguish string and binary types.
159 The type for representing both string and binary types was named **raw**.
160
161 You can pack into and unpack from this old spec using `use_bin_type=False`
162 and `raw=True` options.
163
164 ```pycon
165 >>> import msgpack
166 >>> msgpack.unpackb(msgpack.packb([b'spam', 'eggs'], use_bin_type=False), raw=True)
167 [b'spam', b'eggs']
168 >>> msgpack.unpackb(msgpack.packb([b'spam', 'eggs'], use_bin_type=True), raw=False)
169 [b'spam', 'eggs']
170 ```
171
172 ### ext type
173
174 To use the **ext** type, pass a `msgpack.ExtType` object to the packer.
175
176 ```pycon
177 >>> import msgpack
178 >>> packed = msgpack.packb(msgpack.ExtType(42, b'xyzzy'))
179 >>> msgpack.unpackb(packed)
180 ExtType(code=42, data='xyzzy')
181 ```
182
183 You can use it with `default` and `ext_hook`. See below.
184
185
186 ### Security
187
188 When unpacking data received from an unreliable source, msgpack provides
189 two security options.
190
191 `max_buffer_size` (default: `100*1024*1024`) limits the internal buffer size.
192 It is also used to limit preallocated list sizes.
193
194 `strict_map_key` (default: `True`) limits the type of map keys to bytes and str.
195 While the MessagePack spec doesn't limit map key types,
196 there is a risk of a hash DoS.
197 If you need to support other types for map keys, use `strict_map_key=False`.
198
199
200 ### Performance tips
201
202 CPython's GC starts when the number of allocated objects grows.
203 This means unpacking may trigger unnecessary GC.
204 You can use `gc.disable()` when unpacking a large message.
205
206 A list is the default sequence type in Python.
207 However, a tuple is lighter than a list.
208 You can use `use_list=False` while unpacking when performance is important.
209
210
211 ## Major breaking changes in the history
212
213 ### msgpack 0.5
214
215 The package name on PyPI was changed from `msgpack-python` to `msgpack` in 0.5.
216
217 When upgrading from msgpack-0.4 or earlier, do `pip uninstall msgpack-python` before
218 `pip install -U msgpack`.
219
220
221 ### msgpack 1.0
222
223 * Python 2 support
224
225 * The extension module no longer supports Python 2.
226 The pure Python implementation (`msgpack.fallback`) is used for Python 2.
227
228 * msgpack 1.0.6 drops official support of Python 2.7, as pip and
229 GitHub Action "setup-python" no longer supports Python 2.7.
230
231 * Packer
232
233 * Packer uses `use_bin_type=True` by default.
234 Bytes are encoded in the bin type in MessagePack.
235 * The `encoding` option is removed. UTF-8 is always used.
236
237 * Unpacker
238
239 * Unpacker uses `raw=False` by default. It assumes str values are valid UTF-8 strings
240 and decodes them to Python str (Unicode) objects.
241 * `encoding` option is removed. You can use `raw=True` to support old format (e.g. unpack into bytes, not str).
242 * The default value of `max_buffer_size` is changed from 0 to 100 MiB to avoid DoS attacks.
243 You need to pass `max_buffer_size=0` if you have large but safe data.
244 * The default value of `strict_map_key` is changed to True to avoid hash DoS.
245 You need to pass `strict_map_key=False` if you have data that contain map keys
246 whose type is neither bytes nor str.