gpt4 book ai didi

python - 将 msgpack-python 与嵌套的命名元组一起使用

转载 作者:太空宇宙 更新时间:2023-11-03 14:12:52 25 4
gpt4 key购买 nike

我的数据结构是这样的:

user = UserTuple(
name=u'Anakin', surname=u'Skywalker', birthdate=datetime.date(1981, 7, 25),
profile=ProfileTuple(avatar=u'http://localhost/profile.jpg')
)

我想用 msgpack-python 模块打包这些数据。但是 msgpack 将命名元组转换为列表。是否可以使用 msgpack 像这样打包数据并保留命名元组,就像 pickle/cpickle 一样?

最佳答案

您需要有最新的 msgpack-python 版本。 v0.4.7 不工作。 (目前必须从 master 分支安装)。

import msgpack
from collections import namedtuple

User = namedtuple('User', ['name', 'profile'])
Profile = namedtuple('Profile', ['avatar'])

def ext_pack(x):
if isinstance(x, User):
return msgpack.ExtType(1, msgpack.packb([x[0], x[1]], default=ext_pack, strict_types=True))
elif isinstance(x, Profile):
return msgpack.ExtType(2, msgpack.packb(x[0], default=ext_pack, strict_types=True))
return x

def ext_unpack(code, data):
if code == 1:
name, profile = msgpack.unpackb(data, ext_hook=ext_unpack)
return User(name, profile)
elif code == 2:
avatar = msgpack.unpackb(data, ext_hook=ext_unpack)
return Profile(avatar)
return msgpack.ExtType(code, data)

x = User("me", Profile(234))
s = msgpack.packb([x, [1, x]], default=ext_pack, strict_types=True)
msgpack.unpackb(s, ext_hook=ext_unpack)
>>> [User(name='me', profile=Profile(avatar=234)),
[1, User(name='me', profile=Profile(avatar=234))]]

这里我们将UserProfile分别标记为type code 1、2。或者,您可以将所有 namedtuple 视为相同的类型代码,并将实际类型存储在数据字段中。

关于python - 将 msgpack-python 与嵌套的命名元组一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35863822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com