_deprecation_utils.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # mypy: allow-untyped-defs
  2. from typing import List, Callable
  3. import importlib
  4. import warnings
  5. _MESSAGE_TEMPLATE = r"Usage of '{old_location}' is deprecated; please use '{new_location}' instead."
  6. def lazy_deprecated_import(all: List[str], old_module: str, new_module: str) -> Callable:
  7. r"""Import utility to lazily import deprecated packages / modules / functional.
  8. The old_module and new_module are also used in the deprecation warning defined
  9. by the `_MESSAGE_TEMPLATE`.
  10. Args:
  11. all: The list of the functions that are imported. Generally, the module's
  12. __all__ list of the module.
  13. old_module: Old module location
  14. new_module: New module location / Migrated location
  15. Returns:
  16. Callable to assign to the `__getattr__`
  17. Usage:
  18. # In the `torch/nn/quantized/functional.py`
  19. from torch.nn.utils._deprecation_utils import lazy_deprecated_import
  20. _MIGRATED_TO = "torch.ao.nn.quantized.functional"
  21. __getattr__ = lazy_deprecated_import(
  22. all=__all__,
  23. old_module=__name__,
  24. new_module=_MIGRATED_TO)
  25. """
  26. warning_message = _MESSAGE_TEMPLATE.format(
  27. old_location=old_module,
  28. new_location=new_module)
  29. def getattr_dunder(name):
  30. if name in all:
  31. # We are using the "RuntimeWarning" to make sure it is not
  32. # ignored by default.
  33. warnings.warn(warning_message, RuntimeWarning)
  34. package = importlib.import_module(new_module)
  35. return getattr(package, name)
  36. raise AttributeError(f"Module {new_module!r} has no attribute {name!r}.")
  37. return getattr_dunder