_experimental.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # Copyright 2023-present, the HuggingFace Inc. team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Contains utilities to flag a feature as "experimental" in Huggingface Hub."""
  15. import warnings
  16. from collections.abc import Callable
  17. from functools import wraps
  18. from .. import constants
  19. def experimental(fn: Callable) -> Callable:
  20. """Decorator to flag a feature as experimental.
  21. An experimental feature triggers a warning when used as it might be subject to breaking changes without prior notice
  22. in the future.
  23. Warnings can be disabled by setting `HF_HUB_DISABLE_EXPERIMENTAL_WARNING=1` as environment variable.
  24. Args:
  25. fn (`Callable`):
  26. The function to flag as experimental.
  27. Returns:
  28. `Callable`: The decorated function.
  29. Example:
  30. ```python
  31. >>> from huggingface_hub.utils import experimental
  32. >>> @experimental
  33. ... def my_function():
  34. ... print("Hello world!")
  35. >>> my_function()
  36. UserWarning: 'my_function' is experimental and might be subject to breaking changes in the future without prior
  37. notice. You can disable this warning by setting `HF_HUB_DISABLE_EXPERIMENTAL_WARNING=1` as environment variable.
  38. Hello world!
  39. ```
  40. """
  41. # For classes, put the "experimental" around the "__new__" method => __new__ will be removed in warning message
  42. name = fn.__qualname__[: -len(".__new__")] if fn.__qualname__.endswith(".__new__") else fn.__qualname__
  43. @wraps(fn)
  44. def _inner_fn(*args, **kwargs):
  45. if not constants.HF_HUB_DISABLE_EXPERIMENTAL_WARNING:
  46. warnings.warn(
  47. f"'{name}' is experimental and might be subject to breaking changes in the future without prior notice."
  48. " You can disable this warning by setting `HF_HUB_DISABLE_EXPERIMENTAL_WARNING=1` as environment"
  49. " variable.",
  50. UserWarning,
  51. )
  52. return fn(*args, **kwargs)
  53. return _inner_fn