os.py 978 B

123456789101112131415161718192021222324252627282930313233343536
  1. """
  2. Python polyfills for os
  3. """
  4. from __future__ import annotations
  5. import os
  6. from typing import AnyStr
  7. from ..decorators import substitute_in_graph
  8. __all__ = ["fspath"]
  9. # Copied from os.py in the standard library
  10. @substitute_in_graph(os.fspath, can_constant_fold_through=True)
  11. def fspath(path: AnyStr | os.PathLike[AnyStr]) -> AnyStr:
  12. if isinstance(path, (str, bytes)):
  13. return path
  14. path_type = type(path)
  15. try:
  16. path_repr = path_type.__fspath__(path) # type: ignore[arg-type]
  17. except AttributeError:
  18. if hasattr(path_type, "__fspath__"):
  19. raise
  20. raise TypeError(
  21. f"expected str, bytes or os.PathLike object, not {path_type.__name__}",
  22. ) from None
  23. if isinstance(path_repr, (str, bytes)):
  24. return path_repr # type: ignore[return-value]
  25. raise TypeError(
  26. f"expected {path_type.__name__}.__fspath__() to return str or bytes, "
  27. f"not {type(path_repr).__name__}",
  28. )