_compat.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # -*- coding: utf-8 -*-
  2. """
  3. Some py2/py3 compatibility support based on a stripped down
  4. version of six so we don't have to depend on a specific version
  5. of it.
  6. :copyright: (c) 2013 by Armin Ronacher.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. import sys
  10. PY2 = sys.version_info[0] == 2
  11. VER = sys.version_info
  12. if not PY2:
  13. text_type = str
  14. string_types = (str,)
  15. integer_types = (int,)
  16. iterkeys = lambda d: iter(d.keys()) # noqa
  17. itervalues = lambda d: iter(d.values()) # noqa
  18. iteritems = lambda d: iter(d.items()) # noqa
  19. def as_unicode(s):
  20. if isinstance(s, bytes):
  21. return s.decode("utf-8")
  22. return str(s)
  23. else:
  24. text_type = unicode # noqa
  25. string_types = (str, unicode) # noqa
  26. integer_types = (int, long) # noqa
  27. iterkeys = lambda d: d.iterkeys() # noqa
  28. itervalues = lambda d: d.itervalues() # noqa
  29. iteritems = lambda d: d.iteritems() # noqa
  30. def as_unicode(s):
  31. if isinstance(s, str):
  32. return s.decode("utf-8")
  33. return unicode(s) # noqa
  34. def with_metaclass(meta, *bases):
  35. # This requires a bit of explanation: the basic idea is to make a
  36. # dummy metaclass for one level of class instantiation that replaces
  37. # itself with the actual metaclass. Because of internal type checks
  38. # we also need to make sure that we downgrade the custom metaclass
  39. # for one level to something closer to type (that's why __call__ and
  40. # __init__ comes back from type etc.).
  41. #
  42. # This has the advantage over six.with_metaclass in that it does not
  43. # introduce dummy classes into the final MRO.
  44. class metaclass(meta):
  45. __call__ = type.__call__
  46. __init__ = type.__init__
  47. def __new__(cls, name, this_bases, d):
  48. if this_bases is None:
  49. return type.__new__(cls, name, (), d)
  50. return meta(name, bases, d)
  51. return metaclass("temporary_class", None, {})