Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@

<!-- Changes that improve Black's performance. -->

- Avoid using an extra process when running with only one worker (#4734)

### Output

<!-- Changes to Black's terminal output and error messages -->
Expand Down
23 changes: 15 additions & 8 deletions src/black/concurrency.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
NOTE: this module is only imported if we need to format several files at once.
"""

from __future__ import annotations

import asyncio
import logging
import os
Expand Down Expand Up @@ -80,20 +82,25 @@ def reformat_many(
"""Reformat multiple files using a ProcessPoolExecutor."""
maybe_install_uvloop()

executor: Executor
if workers is None:
workers = int(os.environ.get("BLACK_NUM_WORKERS", 0))
workers = workers or os.cpu_count() or 1
if sys.platform == "win32":
# Work around https://bugs.python.org/issue26903
workers = min(workers, 60)
try:
executor = ProcessPoolExecutor(max_workers=workers)
except (ImportError, NotImplementedError, OSError):
# we arrive here if the underlying system does not support multi-processing
# like in AWS Lambda or Termux, in which case we gracefully fallback to
# a ThreadPoolExecutor with just a single worker (more workers would not do us
# any good due to the Global Interpreter Lock)

executor: Executor | None = None
if workers > 1:
try:
executor = ProcessPoolExecutor(max_workers=workers)
except (ImportError, NotImplementedError, OSError):
# we arrive here if the underlying system does not support multi-processing
# like in AWS Lambda or Termux, in which case we gracefully fallback to
# a ThreadPoolExecutor with just a single worker (more workers would not do
# us any good due to the Global Interpreter Lock)
pass

if executor is None:
executor = ThreadPoolExecutor(max_workers=1)

loop = asyncio.new_event_loop()
Expand Down
Loading