Guest User

Untitled

a guest
Mar 17th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. from urllib.parse import quote, unquote
  2.  
  3.  
  4. def dirty(obj: any):
  5. if isinstance(obj, str):
  6. return quote("S{obj}".format(obj=obj))
  7. elif isinstance(obj, bool):
  8. return "B{v}".format(v=1 if obj else 0)
  9. elif isinstance(obj, int):
  10. return "I{obj}".format(obj=obj)
  11. elif isinstance(obj, float):
  12. return "F{obj}".format(obj=obj)
  13. elif obj is None:
  14. return 'N'
  15. elif isinstance(obj, list):
  16. return quote("L" + ','.join(map(dirty, obj)))
  17. elif isinstance(obj, tuple):
  18. return quote("T" + ','.join(map(dirty, obj)))
  19. elif isinstance(obj, dict):
  20. items = []
  21. for key, value in obj.items():
  22. items.append(dirty(key) + ":" + dirty(value))
  23. return "D" + quote(','.join(items))
  24.  
  25.  
  26. def clean(text: str):
  27. typ, data = text[:1], text[1:]
  28. if typ == 'S':
  29. return unquote(data)
  30. elif typ == 'B':
  31. return bool(data)
  32. elif typ == 'I':
  33. return int(data)
  34. elif typ == 'F':
  35. return float(data)
  36. elif typ == 'N':
  37. return None
  38. elif typ == 'L':
  39. data = unquote(data)
  40. return list(map(clean, data.split(',')))
  41. elif typ == 'T':
  42. data = unquote(data)
  43. return tuple(map(clean, data.split(',')))
  44. elif typ == 'D':
  45. data = unquote(data)
  46. items = data.split(',')
  47. new = dict(map(lambda s: map(unquote, s.split(':')), items))
  48. ret = {}
  49. for key, value in new.items():
  50. ret[clean(key)] = clean(value)
  51. return ret
  52.  
  53.  
  54. if __name__ == '__main__':
  55. stuff = {'A': 5, (4, 5, 7): True}
  56. data = dirty(stuff)
  57. print(data)
  58. print(clean(data))
Add Comment
Please, Sign In to add comment