[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-06-25 09:42:57 +08:00
committed by PyTorch MergeBot
parent 4ca8eecca4
commit 0314c4c101
56 changed files with 165 additions and 145 deletions

View File

@ -1,8 +1,8 @@
import argparse
import os
import pathlib
import re
from collections import Counter, defaultdict, namedtuple
from pathlib import Path
from typing import Dict, List, Optional, Sequence, Set, Union
import yaml
@ -527,7 +527,7 @@ def run(
source_yaml: str, output_dir: str, dry_run: bool, impl_path: Optional[str] = None
) -> None:
# Assumes that this file lives at PYTORCH_ROOT/torchgen/gen_backend_stubs.py
pytorch_root = pathlib.Path(__file__).parent.parent.absolute()
pytorch_root = Path(__file__).absolute().parent.parent
template_dir = os.path.join(pytorch_root, "aten/src/ATen/templates")
def make_file_manager(install_dir: str) -> FileManager: