DESCRIPTION.rst 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. Serpent is a simple serialization library based on ast.literal_eval.
  2. Because it only serializes literals and recreates the objects using ast.literal_eval(),
  3. the serialized data is safe to transport to other machines (over the network for instance)
  4. and de-serialize it there.
  5. *There is also a Java and a .NET (C#) implementation available. This allows for easy data transfer between the various ecosystems.
  6. You can get the full source distribution, a Java .jar file, and a .NET assembly dll.*
  7. The java library can be obtained from Maven central (groupid ``net.razorvine`` artifactid ``serpent``),
  8. and the .NET assembly can be obtained from Nuget.org (package ``Razorvine.Serpent``).
  9. **API**
  10. - ``ser_bytes = serpent.dumps(obj, indent=False, set_literals=True, module_in_classname=False):`` # serialize obj tree to bytes
  11. - ``obj = serpent.loads(ser_bytes)`` # deserialize bytes back into object tree
  12. - You can use ``ast.literal_eval`` yourself to deserialize, but ``serpent.deserialize`` works around a few corner cases. See source for details.
  13. Serpent is more sophisticated than a simple repr() + literal_eval():
  14. - it serializes directly to bytes (utf-8 encoded), instead of a string, so it can immediately be saved to a file or sent over a socket
  15. - it encodes byte-types as base-64 instead of inefficient escaping notation that repr would use (this does mean you have
  16. to base-64 decode these strings manually on the receiving side to get your bytes back.
  17. You can use the serpent.tobytes utility function for this.)
  18. - it contains a few custom serializers for several additional Python types such as uuid, datetime, array and decimal
  19. - it tries to serialize unrecognised types as a dict (you can control this with __getstate__ on your own types)
  20. - it can create a pretty-printed (indented) output for readability purposes
  21. - it outputs the keys of sets and dicts in alphabetical order (when pretty-printing)
  22. - it works around a few quirks of ast.literal_eval() on the various Python implementations
  23. Serpent allows comments in the serialized data (because it is just Python source code).
  24. Serpent can't serialize object graphs (when an object refers to itself); it will then crash with a ValueError pointing out the problem.
  25. Works with Python 2.7+ (including 3.x), IronPython 2.7+, Jython 2.7+.
  26. **FAQ**
  27. - Why not use XML? Answer: because XML.
  28. - Why not use JSON? Answer: because JSON is quite limited in the number of datatypes it supports, and you can't use comments in a JSON file.
  29. - Why not use pickle? Answer: because pickle has security problems.
  30. - Why not use ``repr()``/``ast.literal_eval()``? See above; serpent is a superset of this and provides more convenience. Serpent provides automatic serialization mappings for types other than the builtin primitive types. ``repr()`` can't serialize these to literals that ``ast.literal_eval()`` understands.
  31. - Why not a binary format? Answer: because binary isn't readable by humans.
  32. - But I don't care about readability. Answer: doesn't matter, ``ast.literal_eval()`` wants a literal string, so that is what we produce.
  33. - But I want better performance. Answer: ok, maybe you shouldn't use serpent in this case. Find an efficient binary protocol (protobuf?)
  34. - Why only Python, Java and C#/.NET, but no bindings for insert-favorite-language-here? Answer: I don't speak that language. Maybe you could port serpent yourself?
  35. - Where is the source? It's on Github: https://github.com/irmen/Serpent
  36. - Can I use it everywhere? Sure, as long as you keep the copyright and disclaimer somewhere. See the LICENSE file.
  37. **Demo**
  38. .. code:: python
  39. # This demo script is written for Python 3.2+
  40. # -*- coding: utf-8 -*-
  41. from __future__ import print_function
  42. import ast
  43. import uuid
  44. import datetime
  45. import pprint
  46. import serpent
  47. class DemoClass:
  48. def __init__(self):
  49. self.i=42
  50. self.b=False
  51. data = {
  52. "names": ["Harry", "Sally", "Peter"],
  53. "big": 2**200,
  54. "colorset": { "red", "green" },
  55. "id": uuid.uuid4(),
  56. "timestamp": datetime.datetime.now(),
  57. "class": DemoClass(),
  58. "unicode": "€"
  59. }
  60. # serialize it
  61. ser = serpent.dumps(data, indent=True)
  62. open("data.serpent", "wb").write(ser)
  63. print("Serialized form:")
  64. print(ser.decode("utf-8"))
  65. # read it back
  66. data = serpent.load(open("data.serpent", "rb"))
  67. print("Data:")
  68. pprint.pprint(data)
  69. # you can also use ast.literal_eval if you like
  70. ser_string = open("data.serpent", "r", encoding="utf-8").read()
  71. data2 = ast.literal_eval(ser_string)
  72. assert data2==data
  73. When you run this (with python 3.2+) it prints:
  74. .. code:: python
  75. Serialized form:
  76. # serpent utf-8 python3.2
  77. {
  78. 'big': 1606938044258990275541962092341162602522202993782792835301376,
  79. 'class': {
  80. '__class__': 'DemoClass',
  81. 'b': False,
  82. 'i': 42
  83. },
  84. 'colorset': {
  85. 'green',
  86. 'red'
  87. },
  88. 'id': 'e461378a-201d-4844-8119-7c1570d9d186',
  89. 'names': [
  90. 'Harry',
  91. 'Sally',
  92. 'Peter'
  93. ],
  94. 'timestamp': '2013-04-02T00:23:00.924000',
  95. 'unicode': '€'
  96. }
  97. Data:
  98. {'big': 1606938044258990275541962092341162602522202993782792835301376,
  99. 'class': {'__class__': 'DemoClass', 'b': False, 'i': 42},
  100. 'colorset': {'green', 'red'},
  101. 'id': 'e461378a-201d-4844-8119-7c1570d9d186',
  102. 'names': ['Harry', 'Sally', 'Peter'],
  103. 'timestamp': '2013-04-02T00:23:00.924000',
  104. 'unicode': '€'}