Skip to content

Commit 0567da9

Browse files
authored
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.
1 parent 13e7213 commit 0567da9

File tree

3 files changed

+4
-10
lines changed

3 files changed

+4
-10
lines changed

mypy/report.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ class AbstractReporter(metaclass=ABCMeta):
9999
def __init__(self, reports: Reports, output_dir: str) -> None:
100100
self.output_dir = output_dir
101101
if output_dir != "<memory>":
102-
stats.ensure_dir_exists(output_dir)
102+
os.makedirs(output_dir, exist_ok=True)
103103

104104
@abstractmethod
105105
def on_file(
@@ -737,7 +737,7 @@ def on_file(
737737
if path.startswith(".."):
738738
return
739739
out_path = os.path.join(self.output_dir, "xml", path + ".xml")
740-
stats.ensure_dir_exists(os.path.dirname(out_path))
740+
os.makedirs(os.path.dirname(out_path), exist_ok=True)
741741
last_xml.write(out_path, encoding="utf-8")
742742

743743
def on_finish(self) -> None:
@@ -782,7 +782,7 @@ def on_file(
782782
if path.startswith(".."):
783783
return
784784
out_path = os.path.join(self.output_dir, "html", path + ".html")
785-
stats.ensure_dir_exists(os.path.dirname(out_path))
785+
os.makedirs(os.path.dirname(out_path), exist_ok=True)
786786
transformed_html = bytes(self.xslt_html(last_xml, ext=self.param_html))
787787
with open(out_path, "wb") as out_file:
788788
out_file.write(transformed_html)

mypy/stats.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -477,11 +477,6 @@ def is_complex(t: Type) -> bool:
477477
return is_generic(t) or isinstance(t, (FunctionLike, TupleType, TypeVarType))
478478

479479

480-
def ensure_dir_exists(dir: str) -> None:
481-
if not os.path.exists(dir):
482-
os.makedirs(dir)
483-
484-
485480
def is_special_form_any(t: AnyType) -> bool:
486481
return get_original_any(t).type_of_any == TypeOfAny.special_form
487482

mypy/stubgen.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1833,8 +1833,7 @@ def parse_options(args: list[str]) -> Options:
18331833
parser.error("Cannot specify both --parse-only/--no-analysis and --inspect-mode")
18341834

18351835
# Create the output folder if it doesn't already exist.
1836-
if not os.path.exists(ns.output_dir):
1837-
os.makedirs(ns.output_dir)
1836+
os.makedirs(ns.output_dir, exist_ok=True)
18381837

18391838
return Options(
18401839
pyversion=pyversion,

0 commit comments

Comments
 (0)