_deprecation_utils.py 1.6 KB

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