importer.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. import importlib
  2. from abc import ABC, abstractmethod
  3. from pickle import ( # type: ignore[attr-defined] # type: ignore[attr-defined]
  4. _getattribute,
  5. _Pickler,
  6. whichmodule as _pickle_whichmodule,
  7. )
  8. from types import ModuleType
  9. from typing import Any, Dict, List, Optional, Tuple
  10. from ._mangling import demangle, get_mangle_prefix, is_mangled
  11. __all__ = ["ObjNotFoundError", "ObjMismatchError", "Importer", "OrderedImporter"]
  12. class ObjNotFoundError(Exception):
  13. """Raised when an importer cannot find an object by searching for its name."""
  14. pass
  15. class ObjMismatchError(Exception):
  16. """Raised when an importer found a different object with the same name as the user-provided one."""
  17. pass
  18. class Importer(ABC):
  19. """Represents an environment to import modules from.
  20. By default, you can figure out what module an object belongs by checking
  21. __module__ and importing the result using __import__ or importlib.import_module.
  22. torch.package introduces module importers other than the default one.
  23. Each PackageImporter introduces a new namespace. Potentially a single
  24. name (e.g. 'foo.bar') is present in multiple namespaces.
  25. It supports two main operations:
  26. import_module: module_name -> module object
  27. get_name: object -> (parent module name, name of obj within module)
  28. The guarantee is that following round-trip will succeed or throw an ObjNotFoundError/ObjMisMatchError.
  29. module_name, obj_name = env.get_name(obj)
  30. module = env.import_module(module_name)
  31. obj2 = getattr(module, obj_name)
  32. assert obj1 is obj2
  33. """
  34. modules: Dict[str, ModuleType]
  35. @abstractmethod
  36. def import_module(self, module_name: str) -> ModuleType:
  37. """Import `module_name` from this environment.
  38. The contract is the same as for importlib.import_module.
  39. """
  40. pass
  41. def get_name(self, obj: Any, name: Optional[str] = None) -> Tuple[str, str]:
  42. """Given an object, return a name that can be used to retrieve the
  43. object from this environment.
  44. Args:
  45. obj: An object to get the the module-environment-relative name for.
  46. name: If set, use this name instead of looking up __name__ or __qualname__ on `obj`.
  47. This is only here to match how Pickler handles __reduce__ functions that return a string,
  48. don't use otherwise.
  49. Returns:
  50. A tuple (parent_module_name, attr_name) that can be used to retrieve `obj` from this environment.
  51. Use it like:
  52. mod = importer.import_module(parent_module_name)
  53. obj = getattr(mod, attr_name)
  54. Raises:
  55. ObjNotFoundError: we couldn't retrieve `obj by name.
  56. ObjMisMatchError: we found a different object with the same name as `obj`.
  57. """
  58. if name is None and obj and _Pickler.dispatch.get(type(obj)) is None:
  59. # Honor the string return variant of __reduce__, which will give us
  60. # a global name to search for in this environment.
  61. # TODO: I guess we should do copyreg too?
  62. reduce = getattr(obj, "__reduce__", None)
  63. if reduce is not None:
  64. try:
  65. rv = reduce()
  66. if isinstance(rv, str):
  67. name = rv
  68. except Exception:
  69. pass
  70. if name is None:
  71. name = getattr(obj, "__qualname__", None)
  72. if name is None:
  73. name = obj.__name__
  74. orig_module_name = self.whichmodule(obj, name)
  75. # Demangle the module name before importing. If this obj came out of a
  76. # PackageImporter, `__module__` will be mangled. See mangling.md for
  77. # details.
  78. module_name = demangle(orig_module_name)
  79. # Check that this name will indeed return the correct object
  80. try:
  81. module = self.import_module(module_name)
  82. obj2, _ = _getattribute(module, name)
  83. except (ImportError, KeyError, AttributeError):
  84. raise ObjNotFoundError(
  85. f"{obj} was not found as {module_name}.{name}"
  86. ) from None
  87. if obj is obj2:
  88. return module_name, name
  89. def get_obj_info(obj):
  90. assert name is not None
  91. module_name = self.whichmodule(obj, name)
  92. is_mangled_ = is_mangled(module_name)
  93. location = (
  94. get_mangle_prefix(module_name)
  95. if is_mangled_
  96. else "the current Python environment"
  97. )
  98. importer_name = (
  99. f"the importer for {get_mangle_prefix(module_name)}"
  100. if is_mangled_
  101. else "'sys_importer'"
  102. )
  103. return module_name, location, importer_name
  104. obj_module_name, obj_location, obj_importer_name = get_obj_info(obj)
  105. obj2_module_name, obj2_location, obj2_importer_name = get_obj_info(obj2)
  106. msg = (
  107. f"\n\nThe object provided is from '{obj_module_name}', "
  108. f"which is coming from {obj_location}."
  109. f"\nHowever, when we import '{obj2_module_name}', it's coming from {obj2_location}."
  110. "\nTo fix this, make sure this 'PackageExporter's importer lists "
  111. f"{obj_importer_name} before {obj2_importer_name}."
  112. )
  113. raise ObjMismatchError(msg)
  114. def whichmodule(self, obj: Any, name: str) -> str:
  115. """Find the module name an object belongs to.
  116. This should be considered internal for end-users, but developers of
  117. an importer can override it to customize the behavior.
  118. Taken from pickle.py, but modified to exclude the search into sys.modules
  119. """
  120. module_name = getattr(obj, "__module__", None)
  121. if module_name is not None:
  122. return module_name
  123. # Protect the iteration by using a list copy of self.modules against dynamic
  124. # modules that trigger imports of other modules upon calls to getattr.
  125. for module_name, module in self.modules.copy().items():
  126. if (
  127. module_name == "__main__"
  128. or module_name == "__mp_main__" # bpo-42406
  129. or module is None
  130. ):
  131. continue
  132. try:
  133. if _getattribute(module, name)[0] is obj:
  134. return module_name
  135. except AttributeError:
  136. pass
  137. return "__main__"
  138. class _SysImporter(Importer):
  139. """An importer that implements the default behavior of Python."""
  140. def import_module(self, module_name: str):
  141. return importlib.import_module(module_name)
  142. def whichmodule(self, obj: Any, name: str) -> str:
  143. return _pickle_whichmodule(obj, name)
  144. sys_importer = _SysImporter()
  145. class OrderedImporter(Importer):
  146. """A compound importer that takes a list of importers and tries them one at a time.
  147. The first importer in the list that returns a result "wins".
  148. """
  149. def __init__(self, *args):
  150. self._importers: List[Importer] = list(args)
  151. def _is_torchpackage_dummy(self, module):
  152. """Returns true iff this module is an empty PackageNode in a torch.package.
  153. If you intern `a.b` but never use `a` in your code, then `a` will be an
  154. empty module with no source. This can break cases where we are trying to
  155. re-package an object after adding a real dependency on `a`, since
  156. OrderedImportere will resolve `a` to the dummy package and stop there.
  157. See: https://github.com/pytorch/pytorch/pull/71520#issuecomment-1029603769
  158. """
  159. if not getattr(module, "__torch_package__", False):
  160. return False
  161. if not hasattr(module, "__path__"):
  162. return False
  163. if not hasattr(module, "__file__"):
  164. return True
  165. return module.__file__ is None
  166. def import_module(self, module_name: str) -> ModuleType:
  167. last_err = None
  168. for importer in self._importers:
  169. if not isinstance(importer, Importer):
  170. raise TypeError(
  171. f"{importer} is not a Importer. "
  172. "All importers in OrderedImporter must inherit from Importer."
  173. )
  174. try:
  175. module = importer.import_module(module_name)
  176. if self._is_torchpackage_dummy(module):
  177. continue
  178. return module
  179. except ModuleNotFoundError as err:
  180. last_err = err
  181. if last_err is not None:
  182. raise last_err
  183. else:
  184. raise ModuleNotFoundError(module_name)
  185. def whichmodule(self, obj: Any, name: str) -> str:
  186. for importer in self._importers:
  187. module_name = importer.whichmodule(obj, name)
  188. if module_name != "__main__":
  189. return module_name
  190. return "__main__"