1
0

utils.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import functools
  2. import inspect
  3. import types
  4. import warnings
  5. import sys
  6. def warn(msg):
  7. # type: (str) -> None
  8. warnings.simplefilter("always", DeprecationWarning) # turn off filter
  9. warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
  10. warnings.simplefilter("default", DeprecationWarning) # reset filter
  11. class deprecated(object):
  12. def __init__(self, reason, name=None):
  13. if inspect.isclass(reason) or inspect.isfunction(reason):
  14. raise TypeError("Reason for deprecation must be supplied")
  15. self.reason = reason
  16. self.name = name
  17. def __call__(self, cls_or_func):
  18. if inspect.isfunction(cls_or_func):
  19. fmt = "Call to deprecated function or method {name} ({reason})."
  20. elif inspect.isclass(cls_or_func):
  21. fmt = "Call to deprecated class {name} ({reason})."
  22. else:
  23. raise TypeError(type(cls_or_func))
  24. msg = fmt.format(name=self.name or cls_or_func.__name__, reason=self.reason)
  25. @functools.wraps(cls_or_func)
  26. def new_func(*args, **kwargs):
  27. warn(msg)
  28. return cls_or_func(*args, **kwargs)
  29. return new_func
  30. PY2 = sys.version_info[0] == 2
  31. PY3 = sys.version_info[0] == 3
  32. if PY3:
  33. string_types = (str,) # type: tuple
  34. integer_types = (int,) # type: tuple
  35. class_types = (type,) # type: tuple
  36. text_type = str
  37. binary_type = bytes
  38. else:
  39. string_types = (basestring,) # type: tuple
  40. integer_types = (int, long) # type: tuple
  41. class_types = (type, types.ClassType) # type: tuple
  42. text_type = unicode
  43. binary_type = str