_compat.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. # -*- coding: utf-8 -*-
  2. """
  3. jinja2._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: Copyright 2013 by the Jinja team, see AUTHORS.
  9. :license: BSD, see LICENSE for details.
  10. """
  11. import sys
  12. PY2 = sys.version_info[0] == 2
  13. PYPY = hasattr(sys, 'pypy_translation_info')
  14. _identity = lambda x: x
  15. if not PY2:
  16. unichr = chr
  17. range_type = range
  18. text_type = str
  19. string_types = (str,)
  20. integer_types = (int,)
  21. iterkeys = lambda d: iter(d.keys())
  22. itervalues = lambda d: iter(d.values())
  23. iteritems = lambda d: iter(d.items())
  24. import pickle
  25. from io import BytesIO, StringIO
  26. NativeStringIO = StringIO
  27. def reraise(tp, value, tb=None):
  28. if value.__traceback__ is not tb:
  29. raise value.with_traceback(tb)
  30. raise value
  31. ifilter = filter
  32. imap = map
  33. izip = zip
  34. intern = sys.intern
  35. implements_iterator = _identity
  36. implements_to_string = _identity
  37. encode_filename = _identity
  38. else:
  39. unichr = unichr
  40. text_type = unicode
  41. range_type = xrange
  42. string_types = (str, unicode)
  43. integer_types = (int, long)
  44. iterkeys = lambda d: d.iterkeys()
  45. itervalues = lambda d: d.itervalues()
  46. iteritems = lambda d: d.iteritems()
  47. import cPickle as pickle
  48. from cStringIO import StringIO as BytesIO, StringIO
  49. NativeStringIO = BytesIO
  50. exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')
  51. from itertools import imap, izip, ifilter
  52. intern = intern
  53. def implements_iterator(cls):
  54. cls.next = cls.__next__
  55. del cls.__next__
  56. return cls
  57. def implements_to_string(cls):
  58. cls.__unicode__ = cls.__str__
  59. cls.__str__ = lambda x: x.__unicode__().encode('utf-8')
  60. return cls
  61. def encode_filename(filename):
  62. if isinstance(filename, unicode):
  63. return filename.encode('utf-8')
  64. return filename
  65. def with_metaclass(meta, *bases):
  66. """Create a base class with a metaclass."""
  67. # This requires a bit of explanation: the basic idea is to make a
  68. # dummy metaclass for one level of class instantiation that replaces
  69. # itself with the actual metaclass.
  70. class metaclass(type):
  71. def __new__(cls, name, this_bases, d):
  72. return meta(name, bases, d)
  73. return type.__new__(metaclass, 'temporary_class', (), {})
  74. try:
  75. from urllib.parse import quote_from_bytes as url_quote
  76. except ImportError:
  77. from urllib import quote as url_quote