The min and max clamping in your calc_num_workers function is almost correct, but there's a subtle issue when target is an integer. Let's break it down:
Current Logic:
- If
target is a float, it multiplies the number of available CPUs and clamps the result between min and max.
- If
target is an integer, it uses target directly and clamps it between min and max.
Potential Issue:
When target is an integer, the clamping is applied after target is directly used. However, if target is already outside the [min, max] range, the clamping will correctly adjust it. The issue arises if you expect the min and max constraints to always be enforced, regardless of the type of target.
Example:
- If
target = 2048 (an integer), min = 1, and max = 1024, the function will return 2048 because it directly uses target without clamping in the integer case. This might not be the intended behavior if you always want the result to be within [min, max].
Corrected Logic:
To ensure min and max are always respected, you should clamp the result after determining the number of workers, regardless of whether target is an integer or float. Here's the corrected version:
import builtins
from multiprocessing import cpu_count as process_cpu_count
def calc_num_workers(
target: int | float = 1.0, *, min: int = 1, max: int = 1024
) -> int:
"""
Calculate the number of workers to use based on the target value.
If the target is an integer, it will be used as is.
If the target is a float, it will multiply the number of available CPUs.
The result is clamped between min and max.
"""
num_cpus = process_cpu_count() or 1
calculated_workers = (
int(num_cpus * target) if isinstance(target, float) else target
)
return builtins.min(builtins.max(calculated_workers, min), max)
Explanation of Changes:
- Calculate Workers: First, determine the number of workers based on
target (either directly if it's an integer or by multiplying CPUs if it's a float).
- Clamp the Result: Apply
min and max clamping to the calculated number of workers, ensuring the result is always within the specified range.
This ensures that min and max constraints are always enforced, regardless of the type or value of target.