compat3.py 849 B

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