[BE][Easy] use pathlib.Path instead of dirname / ".." / pardir (#129374)

Changes by apply order:

1. Replace all `".."` and `os.pardir` usage with `os.path.dirname(...)`.
2. Replace nested `os.path.dirname(os.path.dirname(...))` call with `str(Path(...).parent.parent)`.
3. Reorder `.absolute()` ~/ `.resolve()`~ and `.parent`: always resolve the path first.

    `.parent{...}.absolute()` -> `.absolute().parent{...}`

4. Replace chained `.parent x N` with `.parents[${N - 1}]`: the code is easier to read (see 5.)

    `.parent.parent.parent.parent` -> `.parents[3]`

5. ~Replace `.parents[${N - 1}]` with `.parents[${N} - 1]`: the code is easier to read and does not introduce any runtime overhead.~

    ~`.parents[3]` -> `.parents[4 - 1]`~

6. ~Replace `.parents[2 - 1]` with `.parent.parent`: because the code is shorter and easier to read.~

Pull Request resolved: https://github.com/pytorch/pytorch/pull/129374
Approved by: https://github.com/justinchuby, https://github.com/malfet
This commit is contained in:
Xuehai Pan
2024-12-22 00:44:29 +08:00
committed by PyTorch MergeBot
parent 197954e14b
commit 2293fe1024
62 changed files with 119 additions and 133 deletions

View File

@ -26,10 +26,7 @@ try:
PYTORCH_ROOT = result.stdout.decode("utf-8").strip()
except subprocess.CalledProcessError:
# If git is not installed, compute repo root as 3 folders up from this file
path_ = os.path.abspath(__file__)
for _ in range(4):
path_ = os.path.dirname(path_)
PYTORCH_ROOT = path_
PYTORCH_ROOT = str(Path(__file__).absolute().parents[3])
DRY_RUN = False