os.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. # pyrefly: ignore [bad-argument-type]
  11. @substitute_in_graph(os.fspath, can_constant_fold_through=True)
  12. def fspath(path: AnyStr | os.PathLike[AnyStr]) -> AnyStr:
  13. if isinstance(path, (str, bytes)):
  14. # pyrefly: ignore [bad-return]
  15. return path
  16. path_type = type(path)
  17. try:
  18. path_repr = path_type.__fspath__(path) # type: ignore[arg-type]
  19. except AttributeError:
  20. if hasattr(path_type, "__fspath__"):
  21. raise
  22. raise TypeError(
  23. f"expected str, bytes or os.PathLike object, not {path_type.__name__}",
  24. ) from None
  25. if isinstance(path_repr, (str, bytes)):
  26. return path_repr # type: ignore[return-value]
  27. raise TypeError(
  28. f"expected {path_type.__name__}.__fspath__() to return str or bytes, "
  29. f"not {type(path_repr).__name__}",
  30. )