Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- from __future__ import print_function
- import inspect
- import locale
- try:
- unichr
- except NameError:
- unichr = chr # python 3
- try:
- unicode
- except NameError:
- unicode = basestring = str # python 3
- class Test(object):
- def __init__(self, a="a", b="b", c="c", d="d", e="e"):
- self.a = a
- self.b = b
- self.c = c
- self.d = d
- self.e = e
- params = inspect.getargspec(self.__init__)[0][1:]
- self.encode(params)
- print(self.a, self.b, self.c, self.d, self.e)
- print(type(self.a), type(self.b), type(self.c), type(self.d), type(self.e))
- def encode(self, params):
- """encode args of initializer into bytestrings or bytes objects,
- if they are unicode strings. Params can be bytes, str, unicode,
- dict, dict of dics, list of str/bytes/unicode"""
- args = [getattr(self, param) for param in params]
- for param, arg in zip(params, args):
- if isinstance(arg, unicode):
- arg = self._bytify(arg)
- elif isinstance(arg, dict):
- d = {}
- for k, v in arg.items():
- if isinstance(v, dict):
- d[self._bytify(k)] = self.encode(v)
- else:
- d[self._bytify(k)] = self._bytify(v)
- arg = d
- elif isinstance(arg, list):
- arg = [self._bytify(item) for item in arg]
- setattr(self, param, arg)
- return args
- def _bytify(self, arg):
- """turn arg into bytes object (Python 3) or bytestring (Python 2)"""
- try:
- # unicode (python 2) & str (python 3)
- return arg.encode("utf-8")
- except UnicodeDecodeError:
- # str, python 2
- cp = locale.getdefaultlocale()[-1].lower()
- if cp != "utf-8":
- return arg.decode(cp).encode("utf-8")
- return arg
- except AttributeError:
- # bytes, python 3
- return arg # it is a bytestring already
- if __name__ == "__main__":
- t = Test(u"\u0e2d", {u"a": u"b"}, b'\xc3\xa9',
- {u"a": {u"b": b"c"}}, [b"e", u"xx", b'\xc3\xa9'])
Advertisement
Add Comment
Please, Sign In to add comment