utils.py 2.3 KB

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