Skip to content

Commit

Permalink
Prefer exist_ok=True over explicit os.path.exists(...) checks (py…
Browse files Browse the repository at this point in the history
…thon#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 python#16630.
  • Loading branch information
lgeiger authored Dec 9, 2023
1 parent 13e7213 commit 0567da9
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 10 deletions.
6 changes: 3 additions & 3 deletions mypy/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 != "<memory>":
stats.ensure_dir_exists(output_dir)
os.makedirs(output_dir, exist_ok=True)

@abstractmethod
def on_file(
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
5 changes: 0 additions & 5 deletions mypy/stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 1 addition & 2 deletions mypy/stubgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit 0567da9

Please sign in to comment.