Is there a standalone Python type conversion library?

后端 未结 3 1044
春和景丽
春和景丽 2021-01-27 08:49

Are there any standalone type conversion libraries?

I have a data storage system that only understands bytes/strings, but I can tag metadata such as the type to be conve

3条回答
  •  没有蜡笔的小新
    2021-01-27 09:10

    You've got two options, either use the struct or pickle modules.

    With struct you specify a format and it compacts your data to byte array. This is useful for working with C structures or writing to networked apps that require are binary protocol.

    pickle can automatically serialise and deserialise complex Python structures to a string. There are some caveats so it's best read the documentation. I think this is the most likely the library you want.

    >>> import pickle
    >>> v = pickle.dumps(123)
    >>> v
    'I123\n.'
    >>> pickle.loads(v)
    123
    >>> v = pickle.dumps({"abc": 123})
    >>> v
    "(dp0\nS'abc'\np1\nI123\ns."
    >>> pickle.loads(v)
    {'abc': 123}
    

提交回复
热议问题