Skip to content

Instantly share code, notes, and snippets.

@janzhen
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save janzhen/73041f09307863bd3457 to your computer and use it in GitHub Desktop.

Select an option

Save janzhen/73041f09307863bd3457 to your computer and use it in GitHub Desktop.
convert encoding
import collections
def convert(data, charset, func):
from functools import partial
convert_charset_func = partial(convert, charset=charset, func=func)
if isinstance(data, basestring):
return getattr(data, func)(charset)
elif isinstance(data, collections.Mapping):
return type(data)(map(convert_charset_func, data.iteritems()))
elif isinstance(data, collections.Iterable):
return type(data)(map(convert_charset_func, data))
else:
return data
decode_charset = lambda data, charset: convert(data, charset, 'decode')
encode_charset = lambda data, charset: convert(data, charset, 'encode')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment