Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from urllib.parse import quote, unquote
- def dirty(obj: any):
- if isinstance(obj, str):
- return quote("S{obj}".format(obj=obj))
- elif isinstance(obj, bool):
- return "B{v}".format(v=1 if obj else 0)
- elif isinstance(obj, int):
- return "I{obj}".format(obj=obj)
- elif isinstance(obj, float):
- return "F{obj}".format(obj=obj)
- elif obj is None:
- return 'N'
- elif isinstance(obj, list):
- return quote("L" + ','.join(map(dirty, obj)))
- elif isinstance(obj, tuple):
- return quote("T" + ','.join(map(dirty, obj)))
- elif isinstance(obj, dict):
- items = []
- for key, value in obj.items():
- items.append(dirty(key) + ":" + dirty(value))
- return "D" + quote(','.join(items))
- def clean(text: str):
- typ, data = text[:1], text[1:]
- if typ == 'S':
- return unquote(data)
- elif typ == 'B':
- return bool(data)
- elif typ == 'I':
- return int(data)
- elif typ == 'F':
- return float(data)
- elif typ == 'N':
- return None
- elif typ == 'L':
- data = unquote(data)
- return list(map(clean, data.split(',')))
- elif typ == 'T':
- data = unquote(data)
- return tuple(map(clean, data.split(',')))
- elif typ == 'D':
- data = unquote(data)
- items = data.split(',')
- new = dict(map(lambda s: map(unquote, s.split(':')), items))
- ret = {}
- for key, value in new.items():
- ret[clean(key)] = clean(value)
- return ret
- if __name__ == '__main__':
- stuff = {'A': 5, (4, 5, 7): True}
- data = dirty(stuff)
- print(data)
- print(clean(data))
Add Comment
Please, Sign In to add comment