deprecation.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. # Copyright 2024 The HuggingFace Team. All rights reserved.
  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. import inspect
  15. import warnings
  16. from functools import wraps
  17. from typing import Optional
  18. import packaging.version
  19. from .. import __version__
  20. from . import ExplicitEnum
  21. class Action(ExplicitEnum):
  22. NONE = "none"
  23. NOTIFY = "notify"
  24. NOTIFY_ALWAYS = "notify_always"
  25. RAISE = "raise"
  26. def deprecate_kwarg(
  27. old_name: str,
  28. version: str,
  29. new_name: Optional[str] = None,
  30. warn_if_greater_or_equal_version: bool = False,
  31. raise_if_greater_or_equal_version: bool = False,
  32. raise_if_both_names: bool = False,
  33. additional_message: Optional[str] = None,
  34. ):
  35. """
  36. Function or method decorator to notify users about deprecated keyword arguments, replacing them with a new name if specified.
  37. This decorator allows you to:
  38. - Notify users when a keyword argument is deprecated.
  39. - Automatically replace deprecated keyword arguments with new ones.
  40. - Raise an error if deprecated arguments are used, depending on the specified conditions.
  41. By default, the decorator notifies the user about the deprecated argument while the `transformers.__version__` < specified `version`
  42. in the decorator. To keep notifications with any version `warn_if_greater_or_equal_version=True` can be set.
  43. Parameters:
  44. old_name (`str`):
  45. Name of the deprecated keyword argument.
  46. version (`str`):
  47. The version in which the keyword argument was (or will be) deprecated.
  48. new_name (`Optional[str]`, *optional*):
  49. The new name for the deprecated keyword argument. If specified, the deprecated keyword argument will be replaced with this new name.
  50. warn_if_greater_or_equal_version (`bool`, *optional*, defaults to `False`):
  51. Whether to show warning if current `transformers` version is greater or equal to the deprecated version.
  52. raise_if_greater_or_equal_version (`bool`, *optional*, defaults to `False`):
  53. Whether to raise `ValueError` if current `transformers` version is greater or equal to the deprecated version.
  54. raise_if_both_names (`bool`, *optional*, defaults to `False`):
  55. Whether to raise `ValueError` if both deprecated and new keyword arguments are set.
  56. additional_message (`Optional[str]`, *optional*):
  57. An additional message to append to the default deprecation message.
  58. Raises:
  59. ValueError:
  60. If raise_if_greater_or_equal_version is True and the current version is greater than or equal to the deprecated version, or if raise_if_both_names is True and both old and new keyword arguments are provided.
  61. Returns:
  62. Callable:
  63. A wrapped function that handles the deprecated keyword arguments according to the specified parameters.
  64. Example usage with renaming argument:
  65. ```python
  66. @deprecate_kwarg("reduce_labels", new_name="do_reduce_labels", version="6.0.0")
  67. def my_function(do_reduce_labels):
  68. print(do_reduce_labels)
  69. my_function(reduce_labels=True) # Will show a deprecation warning and use do_reduce_labels=True
  70. ```
  71. Example usage without renaming argument:
  72. ```python
  73. @deprecate_kwarg("max_size", version="6.0.0")
  74. def my_function(max_size):
  75. print(max_size)
  76. my_function(max_size=1333) # Will show a deprecation warning
  77. ```
  78. """
  79. deprecated_version = packaging.version.parse(version)
  80. current_version = packaging.version.parse(__version__)
  81. is_greater_or_equal_version = current_version >= deprecated_version
  82. if is_greater_or_equal_version:
  83. version_message = f"and removed starting from version {version}"
  84. else:
  85. version_message = f"and will be removed in version {version}"
  86. def wrapper(func):
  87. # Required for better warning message
  88. sig = inspect.signature(func)
  89. function_named_args = set(sig.parameters.keys())
  90. is_instance_method = "self" in function_named_args
  91. is_class_method = "cls" in function_named_args
  92. @wraps(func)
  93. def wrapped_func(*args, **kwargs):
  94. # Get class + function name (just for better warning message)
  95. func_name = func.__name__
  96. if is_instance_method:
  97. func_name = f"{args[0].__class__.__name__}.{func_name}"
  98. elif is_class_method:
  99. func_name = f"{args[0].__name__}.{func_name}"
  100. minimum_action = Action.NONE
  101. message = None
  102. # deprecated kwarg and its new version are set for function call -> replace it with new name
  103. if old_name in kwargs and new_name in kwargs:
  104. minimum_action = Action.RAISE if raise_if_both_names else Action.NOTIFY_ALWAYS
  105. message = f"Both `{old_name}` and `{new_name}` are set for `{func_name}`. Using `{new_name}={kwargs[new_name]}` and ignoring deprecated `{old_name}={kwargs[old_name]}`."
  106. kwargs.pop(old_name)
  107. # only deprecated kwarg is set for function call -> replace it with new name
  108. elif old_name in kwargs and new_name is not None and new_name not in kwargs:
  109. minimum_action = Action.NOTIFY
  110. message = f"`{old_name}` is deprecated {version_message} for `{func_name}`. Use `{new_name}` instead."
  111. kwargs[new_name] = kwargs.pop(old_name)
  112. # deprecated kwarg is not set for function call and new name is not specified -> just notify
  113. elif old_name in kwargs:
  114. minimum_action = Action.NOTIFY
  115. message = f"`{old_name}` is deprecated {version_message} for `{func_name}`."
  116. if message is not None and additional_message is not None:
  117. message = f"{message} {additional_message}"
  118. # update minimum_action if argument is ALREADY deprecated (current version >= deprecated version)
  119. if is_greater_or_equal_version:
  120. # change to (NOTIFY, NOTIFY_ALWAYS) -> RAISE if specified
  121. # in case we want to raise error for already deprecated arguments
  122. if raise_if_greater_or_equal_version and minimum_action != Action.NONE:
  123. minimum_action = Action.RAISE
  124. # change to NOTIFY -> NONE if specified (NOTIFY_ALWAYS can't be changed to NONE)
  125. # in case we want to ignore notifications for already deprecated arguments
  126. elif not warn_if_greater_or_equal_version and minimum_action == Action.NOTIFY:
  127. minimum_action = Action.NONE
  128. # raise error or notify user
  129. if minimum_action == Action.RAISE:
  130. raise ValueError(message)
  131. elif minimum_action in (Action.NOTIFY, Action.NOTIFY_ALWAYS):
  132. # DeprecationWarning is ignored by default, so we use FutureWarning instead
  133. warnings.warn(message, FutureWarning, stacklevel=2)
  134. return func(*args, **kwargs)
  135. return wrapped_func
  136. return wrapper