_experimental.py 2.4 KB

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