From 0567da99784c376e723907daf4f16df2f03368c1 Mon Sep 17 00:00:00 2001 From: Lukas Geiger Date: Sat, 9 Dec 2023 20:32:42 +0000 Subject: [PATCH] Prefer `exist_ok=True` over explicit `os.path.exists(...)` checks (#16642) This PR replaces explicit `os.path.exists(...)` checks with `os.makedirs(..., exist_ok=True)` where possible. This removes the need for an extra existence check and slightly simplifies the code. This can also prevent race conditions like #16630. --- mypy/report.py | 6 +++--- mypy/stats.py | 5 ----- mypy/stubgen.py | 3 +-- 3 files changed, 4 insertions(+), 10 deletions(-) diff --git a/mypy/report.py b/mypy/report.py index 86fcee0521a6..764cfec7799a 100644 --- a/mypy/report.py +++ b/mypy/report.py @@ -99,7 +99,7 @@ class AbstractReporter(metaclass=ABCMeta): def __init__(self, reports: Reports, output_dir: str) -> None: self.output_dir = output_dir if output_dir != "": - stats.ensure_dir_exists(output_dir) + os.makedirs(output_dir, exist_ok=True) @abstractmethod def on_file( @@ -737,7 +737,7 @@ def on_file( if path.startswith(".."): return out_path = os.path.join(self.output_dir, "xml", path + ".xml") - stats.ensure_dir_exists(os.path.dirname(out_path)) + os.makedirs(os.path.dirname(out_path), exist_ok=True) last_xml.write(out_path, encoding="utf-8") def on_finish(self) -> None: @@ -782,7 +782,7 @@ def on_file( if path.startswith(".."): return out_path = os.path.join(self.output_dir, "html", path + ".html") - stats.ensure_dir_exists(os.path.dirname(out_path)) + os.makedirs(os.path.dirname(out_path), exist_ok=True) transformed_html = bytes(self.xslt_html(last_xml, ext=self.param_html)) with open(out_path, "wb") as out_file: out_file.write(transformed_html) diff --git a/mypy/stats.py b/mypy/stats.py index b8803e03b9d2..b167a41b0e34 100644 --- a/mypy/stats.py +++ b/mypy/stats.py @@ -477,11 +477,6 @@ def is_complex(t: Type) -> bool: return is_generic(t) or isinstance(t, (FunctionLike, TupleType, TypeVarType)) -def ensure_dir_exists(dir: str) -> None: - if not os.path.exists(dir): - os.makedirs(dir) - - def is_special_form_any(t: AnyType) -> bool: return get_original_any(t).type_of_any == TypeOfAny.special_form diff --git a/mypy/stubgen.py b/mypy/stubgen.py index 23b5fde9dff2..7ec3d7069fb2 100755 --- a/mypy/stubgen.py +++ b/mypy/stubgen.py @@ -1833,8 +1833,7 @@ def parse_options(args: list[str]) -> Options: parser.error("Cannot specify both --parse-only/--no-analysis and --inspect-mode") # Create the output folder if it doesn't already exist. - if not os.path.exists(ns.output_dir): - os.makedirs(ns.output_dir) + os.makedirs(ns.output_dir, exist_ok=True) return Options( pyversion=pyversion,