_importlib.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import _warnings
  2. import os.path
  3. # note: implementations
  4. # copied from cpython's import code
  5. # _zip_searchorder defines how we search for a module in the Zip
  6. # archive: we first search for a package __init__, then for
  7. # non-package .pyc, and .py entries. The .pyc entries
  8. # are swapped by initzipimport() if we run in optimized mode. Also,
  9. # '/' is replaced by path_sep there.
  10. _zip_searchorder = (
  11. ("/__init__.py", True),
  12. (".py", False),
  13. )
  14. # Replace any occurrences of '\r\n?' in the input string with '\n'.
  15. # This converts DOS and Mac line endings to Unix line endings.
  16. def _normalize_line_endings(source):
  17. source = source.replace(b"\r\n", b"\n")
  18. source = source.replace(b"\r", b"\n")
  19. return source
  20. def _resolve_name(name, package, level):
  21. """Resolve a relative module name to an absolute one."""
  22. bits = package.rsplit(".", level - 1)
  23. if len(bits) < level:
  24. raise ValueError("attempted relative import beyond top-level package")
  25. base = bits[0]
  26. return "{}.{}".format(base, name) if name else base
  27. def _sanity_check(name, package, level):
  28. """Verify arguments are "sane"."""
  29. if not isinstance(name, str):
  30. raise TypeError("module name must be str, not {}".format(type(name)))
  31. if level < 0:
  32. raise ValueError("level must be >= 0")
  33. if level > 0:
  34. if not isinstance(package, str):
  35. raise TypeError("__package__ not set to a string")
  36. elif not package:
  37. raise ImportError(
  38. "attempted relative import with no known parent " "package"
  39. )
  40. if not name and level == 0:
  41. raise ValueError("Empty module name")
  42. def _calc___package__(globals):
  43. """Calculate what __package__ should be.
  44. __package__ is not guaranteed to be defined or could be set to None
  45. to represent that its proper value is unknown.
  46. """
  47. package = globals.get("__package__")
  48. spec = globals.get("__spec__")
  49. if package is not None:
  50. if spec is not None and package != spec.parent:
  51. _warnings.warn(
  52. "__package__ != __spec__.parent " f"({package!r} != {spec.parent!r})",
  53. ImportWarning,
  54. stacklevel=3,
  55. )
  56. return package
  57. elif spec is not None:
  58. return spec.parent
  59. else:
  60. _warnings.warn(
  61. "can't resolve package from __spec__ or __package__, "
  62. "falling back on __name__ and __path__",
  63. ImportWarning,
  64. stacklevel=3,
  65. )
  66. package = globals["__name__"]
  67. if "__path__" not in globals:
  68. package = package.rpartition(".")[0]
  69. return package
  70. def _normalize_path(path):
  71. """Normalize a path by ensuring it is a string.
  72. If the resulting string contains path separators, an exception is raised.
  73. """
  74. parent, file_name = os.path.split(path)
  75. if parent:
  76. raise ValueError("{!r} must be only a file name".format(path))
  77. else:
  78. return file_name