You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
2.1 KiB

4 years ago
  1. import sys
  2. import inspect
  3. PY2 = sys.version_info[0] == 2
  4. def with_metaclass(meta, *bases):
  5. # Taken from flask/six.
  6. class metaclass(meta):
  7. def __new__(cls, name, this_bases, d):
  8. return meta(name, bases, d)
  9. return type.__new__(metaclass, 'temporary_class', (), {})
  10. if PY2:
  11. text_type = unicode
  12. string_type = basestring
  13. from itertools import izip_longest as zip_longest
  14. def with_str_method(cls):
  15. """Class decorator that handles __str__ compat between py2 and py3."""
  16. # In python2, the __str__ should be __unicode__
  17. # and __str__ should return bytes.
  18. cls.__unicode__ = cls.__str__
  19. def __str__(self):
  20. return self.__unicode__().encode('utf-8')
  21. cls.__str__ = __str__
  22. return cls
  23. def with_repr_method(cls):
  24. """Class decorator that handle __repr__ with py2 and py3."""
  25. # This is almost the same thing as with_str_method *except*
  26. # it uses the unicode_escape encoding. This also means we need to be
  27. # careful encoding the input multiple times, so we only encode
  28. # if we get a unicode type.
  29. original_repr_method = cls.__repr__
  30. def __repr__(self):
  31. original_repr = original_repr_method(self)
  32. if isinstance(original_repr, text_type):
  33. original_repr = original_repr.encode('unicode_escape')
  34. return original_repr
  35. cls.__repr__ = __repr__
  36. return cls
  37. def get_methods(cls):
  38. for name, method in inspect.getmembers(cls,
  39. predicate=inspect.ismethod):
  40. yield name, method
  41. else:
  42. text_type = str
  43. string_type = str
  44. from itertools import zip_longest
  45. def with_str_method(cls):
  46. # In python3, we don't need to do anything, we return a str type.
  47. return cls
  48. def with_repr_method(cls):
  49. return cls
  50. def get_methods(cls):
  51. for name, method in inspect.getmembers(cls,
  52. predicate=inspect.isfunction):
  53. yield name, method