MCPcopy Index your code
hub / github.com/python/mypy / write_file

Function write_file

mypyc/build.py:425–450  ·  view source on GitHub ↗

Write data into a file. If the file already exists and has the same contents we want to write, skip writing so as to preserve the mtime and avoid triggering recompilation.

(path: str, contents: str)

Source from the content-addressed store, hash-verified

423
424
425def write_file(path: str, contents: str) -> None:
426 """Write data into a file.
427
428 If the file already exists and has the same contents we
429 want to write, skip writing so as to preserve the mtime
430 and avoid triggering recompilation.
431 """
432 # We encode it ourselves and open the files as binary to avoid windows
433 # newline translation
434 encoded_contents = contents.encode("utf-8")
435 try:
436 with open(path, "rb") as f:
437 old_contents: bytes | None = f.read()
438 except OSError:
439 old_contents = None
440 if old_contents != encoded_contents:
441 os.makedirs(os.path.dirname(path), exist_ok=True)
442 with open(path, "wb") as g:
443 g.write(encoded_contents)
444
445 # Fudge the mtime forward because otherwise when two builds happen close
446 # together (like in a test) setuptools might not realize the source is newer
447 # than the new artifact.
448 # XXX: This is bad though.
449 new_mtime = os.stat(path).st_mtime + 1
450 os.utime(path, times=(new_mtime, new_mtime))
451
452
453_MYPYC_EXTENSION_MARKER = "_mypyc_skip_redundant_inplace_copy"

Callers 3

mypyc_buildFunction · 0.85
mypycifyFunction · 0.85

Calls 3

encodeMethod · 0.80
readMethod · 0.45
writeMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…