compat3.py 903 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import sys
  2. __all__ = ['b', 'basestring_', 'bytes', 'unicode_', 'next', 'is_unicode']
  3. if sys.version < "3":
  4. b = bytes = str
  5. basestring_ = basestring
  6. unicode_ = unicode
  7. else:
  8. def b(s):
  9. if isinstance(s, str):
  10. return s.encode('latin1')
  11. return bytes(s)
  12. basestring_ = (bytes, str)
  13. bytes = bytes
  14. unicode_ = str
  15. text = str
  16. if sys.version < "3":
  17. def next(obj):
  18. return obj.next()
  19. else:
  20. next = next
  21. if sys.version < "3":
  22. def is_unicode(obj):
  23. return isinstance(obj, unicode)
  24. else:
  25. def is_unicode(obj):
  26. return isinstance(obj, str)
  27. def coerce_text(v):
  28. if not isinstance(v, basestring_):
  29. if sys.version < "3":
  30. attr = '__unicode__'
  31. else:
  32. attr = '__str__'
  33. if hasattr(v, attr):
  34. return unicode(v)
  35. else:
  36. return bytes(v)
  37. return v