compat.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2016 Andi Albrecht, albrecht.andi@gmail.com
  4. #
  5. # This module is part of python-sqlparse and is released under
  6. # the BSD License: http://www.opensource.org/licenses/bsd-license.php
  7. """Python 2/3 compatibility.
  8. This module only exists to avoid a dependency on six
  9. for very trivial stuff. We only need to take care of
  10. string types, buffers and metaclasses.
  11. Parts of the code is copied directly from six:
  12. https://bitbucket.org/gutworth/six
  13. """
  14. import sys
  15. PY2 = sys.version_info[0] == 2
  16. PY3 = sys.version_info[0] == 3
  17. if PY3:
  18. def u(s, encoding=None):
  19. return str(s)
  20. def unicode_compatible(cls):
  21. return cls
  22. text_type = str
  23. string_types = (str,)
  24. from io import StringIO
  25. elif PY2:
  26. def u(s, encoding=None):
  27. encoding = encoding or 'unicode-escape'
  28. try:
  29. return unicode(s)
  30. except UnicodeDecodeError:
  31. return unicode(s, encoding)
  32. def unicode_compatible(cls):
  33. cls.__unicode__ = cls.__str__
  34. cls.__str__ = lambda x: x.__unicode__().encode('utf-8')
  35. return cls
  36. text_type = unicode
  37. string_types = (str, unicode,)
  38. from StringIO import StringIO