pw_build: Mypy cache dir control

Change-Id: Icbcf6235a967827209d5705130496a0f60a919e7
Reviewed-on: https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/127096
Pigweed-Auto-Submit: Anthony DiGirolamo <tonymd@google.com>
Commit-Queue: Auto-Submit <auto-submit@pigweed.google.com.iam.gserviceaccount.com>
Reviewed-by: Wyatt Hepler <hepler@google.com>
diff --git a/docs/BUILD.gn b/docs/BUILD.gn
index 7da1f68..2162f9e 100644
--- a/docs/BUILD.gn
+++ b/docs/BUILD.gn
@@ -35,6 +35,7 @@
     "images/pw_watch_on_device_demo.gif",
     "images/pw_watch_test_demo.gif",
     "images/stm32f429i-disc1_connected.jpg",
+    "$dir_pw_build/python.gni",
   ]
   sources = [
     "code_of_conduct.rst",
diff --git a/docs/python_build.rst b/docs/python_build.rst
index c3e2391..8c8848a 100644
--- a/docs/python_build.rst
+++ b/docs/python_build.rst
@@ -474,6 +474,14 @@
 
 Packages may opt out of static analysis as necessary.
 
+In addition to user specified ``mypy.ini`` files some arguments are always
+passed to ``mypy`` by default. They can be seen in this excerpt of
+``//pw_build/python.gni`` below:
+
+.. literalinclude:: pw_build/python.gni
+   :start-after: [default-mypy-args]
+   :end-before: [default-mypy-args]
+
 Building Python wheels
 ^^^^^^^^^^^^^^^^^^^^^^
 `Wheels <https://wheel.readthedocs.io/en/stable/>`_ are the standard format for
diff --git a/pw_build/python.gni b/pw_build/python.gni
index 357f375..8e54086 100644
--- a/pw_build/python.gni
+++ b/pw_build/python.gni
@@ -68,6 +68,8 @@
 template("_pw_python_static_analysis_mypy") {
   pw_python_action(target_name) {
     module = "mypy"
+
+    # DOCSTAG: [default-mypy-args]
     args = [
       "--pretty",
       "--show-error-codes",
@@ -76,8 +78,19 @@
       #     mypy 0.991. This caused problems in some configurations, so return
       #     to the prior behavior for now.
       "--no-namespace-packages",
+
+      # Use a mypy cache dir for this target only to avoid cache conflicts in
+      # parallel mypy invocations.
+      "--cache-dir",
+      rebase_path(target_out_dir, root_build_dir) + "/.mypy_cache",
     ]
 
+    # Use this environment variable to force mypy to colorize output.
+    # See https://github.com/python/mypy/issues/7771
+    environment = [ "MYPY_FORCE_COLOR=1" ]
+
+    # DOCSTAG: [default-mypy-args]
+
     if (defined(invoker.mypy_ini)) {
       args +=
           [ "--config-file=" + rebase_path(invoker.mypy_ini, root_build_dir) ]
@@ -86,10 +99,6 @@
 
     args += rebase_path(invoker.sources, root_build_dir)
 
-    # Use this environment variable to force mypy to colorize output.
-    # See https://github.com/python/mypy/issues/7771
-    environment = [ "MYPY_FORCE_COLOR=1" ]
-
     stamp = true
 
     deps = invoker.deps