Guest User

Polymorphic function

a guest
Sep 7th, 2013
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.24 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. from __future__ import print_function
  4. import inspect
  5. import locale
  6.  
  7. try:
  8.     unichr
  9. except NameError:
  10.     unichr = chr  # python 3
  11.  
  12. try:
  13.     unicode
  14. except NameError:
  15.     unicode = basestring = str  # python 3
  16.  
  17. class Test(object):
  18.  
  19.     def __init__(self, a="a", b="b", c="c", d="d", e="e"):
  20.         self.a = a
  21.         self.b = b
  22.         self.c = c
  23.         self.d = d
  24.         self.e = e
  25.         params = inspect.getargspec(self.__init__)[0][1:]
  26.         self.encode(params)
  27.         print(self.a, self.b, self.c, self.d, self.e)
  28.         print(type(self.a), type(self.b), type(self.c), type(self.d), type(self.e))
  29.        
  30.     def encode(self, params):
  31.         """encode args of initializer into bytestrings or bytes objects,
  32.        if they are unicode strings. Params can be bytes, str, unicode,
  33.        dict, dict of dics, list of str/bytes/unicode"""
  34.         args = [getattr(self, param) for param in params]
  35.         for param, arg in zip(params, args):
  36.             if isinstance(arg, unicode):
  37.                 arg = self._bytify(arg)
  38.             elif isinstance(arg, dict):
  39.                 d = {}
  40.                 for k, v in arg.items():
  41.                     if isinstance(v, dict):
  42.                         d[self._bytify(k)] = self.encode(v)
  43.                     else:
  44.                         d[self._bytify(k)] = self._bytify(v)
  45.                 arg = d
  46.             elif isinstance(arg, list):
  47.                 arg = [self._bytify(item) for item in arg]
  48.             setattr(self, param, arg)
  49.         return args
  50.  
  51.     def _bytify(self, arg):
  52.         """turn arg into bytes object (Python 3) or bytestring (Python 2)"""
  53.         try:
  54.             # unicode (python 2) & str (python 3)
  55.             return arg.encode("utf-8")
  56.         except UnicodeDecodeError:
  57.             # str, python 2
  58.             cp = locale.getdefaultlocale()[-1].lower()
  59.             if cp != "utf-8":
  60.                 return arg.decode(cp).encode("utf-8")
  61.             return arg
  62.         except AttributeError:
  63.             # bytes, python 3
  64.             return arg # it is a bytestring already
  65.  
  66. if __name__ == "__main__":
  67.     t = Test(u"\u0e2d", {u"a": u"b"}, b'\xc3\xa9',
  68.              {u"a": {u"b": b"c"}}, [b"e", u"xx", b'\xc3\xa9'])
Advertisement
Add Comment
Please, Sign In to add comment