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