utils.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import functools
  2. import warnings
  3. class jupyterlab_deprecation(Warning):
  4. """Create our own deprecation class, since Python >= 2.7
  5. silences deprecations by default.
  6. """
  7. pass
  8. class deprecated(object):
  9. """Decorator to mark deprecated functions with warning.
  10. Adapted from `scikit-image/skimage/_shared/utils.py`.
  11. Parameters
  12. ----------
  13. alt_func : str
  14. If given, tell user what function to use instead.
  15. behavior : {'warn', 'raise'}
  16. Behavior during call to deprecated function: 'warn' = warn user that
  17. function is deprecated; 'raise' = raise error.
  18. removed_version : str
  19. The package version in which the deprecated function will be removed.
  20. """
  21. def __init__(self, alt_func=None, behavior='warn', removed_version=None):
  22. self.alt_func = alt_func
  23. self.behavior = behavior
  24. self.removed_version = removed_version
  25. def __call__(self, func):
  26. alt_msg = ''
  27. if self.alt_func is not None:
  28. alt_msg = ' Use ``%s`` instead.' % self.alt_func
  29. rmv_msg = ''
  30. if self.removed_version is not None:
  31. rmv_msg = (' and will be removed in version %s' %
  32. self.removed_version)
  33. msg = ('Function ``%s`` is deprecated' % func.__name__ +
  34. rmv_msg + '.' + alt_msg)
  35. @functools.wraps(func)
  36. def wrapped(*args, **kwargs):
  37. if self.behavior == 'warn':
  38. func_code = func.__code__
  39. warnings.simplefilter('always', jupyterlab_deprecation)
  40. warnings.warn_explicit(msg,
  41. category=jupyterlab_deprecation,
  42. filename=func_code.co_filename,
  43. lineno=func_code.co_firstlineno + 1)
  44. elif self.behavior == 'raise':
  45. raise jupyterlab_deprecation(msg)
  46. return func(*args, **kwargs)
  47. # modify doc string to display deprecation warning
  48. doc = '**Deprecated function**.' + alt_msg
  49. if wrapped.__doc__ is None:
  50. wrapped.__doc__ = doc
  51. else:
  52. wrapped.__doc__ = doc + '\n\n ' + wrapped.__doc__
  53. return wrapped