_compat.py 2.1 KB

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