Skip to content

Instantly share code, notes, and snippets.

@Zwork101
Created March 8, 2018 13:01
Show Gist options
  • Save Zwork101/aa704c6e112d3da71a0df0f70420e27a to your computer and use it in GitHub Desktop.
Save Zwork101/aa704c6e112d3da71a0df0f70420e27a to your computer and use it in GitHub Desktop.
custom sterilizer
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))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment