The calc_num_workers function is designed to determine the appropriate number of workers based on a target value, which can be either an integer or a float. The function also includes optional min and max parameters to clamp the result within a valid range. The current implementation of the min/max clamping logic is correct, and here's why:
Function Overview
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.
"""
return builtins.min(
builtins.max(
(
int((process_cpu_count() or 1) * target)
if isinstance(target, float)
else target
),
min,
),
max,
)
Key Logic Breakdown
-
Target Interpretation:
- If
target is a float, it multiplies the number of available CPUs (process_cpu_count()), and the result is cast to an integer.
- If
target is an integer, it is used directly.
-
Clamping Logic:
- The result of the above computation is first passed through
max(..., min) to ensure it is not less than min.
- The result of that is then passed through
min(..., max) to ensure it is not greater than max.
This is effectively equivalent to:
result = max(val, min)
result = min(result, max)
Which ensures the final result is clamped between min and max.
Correctness of Clamping
Let’s analyze the logic in terms of the order of operations and how it enforces the desired constraints.
- Step 1: Compute the base value (
val) based on the target.
- Step 2: Ensure
val >= min by using max(val, min).
- Step 3: Ensure
val <= max by using min(max_result, max).
This is a standard and correct way to clamp a value between two bounds. The use of max and min in sequence guarantees that the result is always within the [min, max] range, regardless of the initial value.
Edge Case Examples
-
Target is a float that results in a value below min:
target = 0.1
process_cpu_count() = 1
val = int(1 * 0.1) = 0
result = max(0, min=1) = 1
result = min(1, max=1024) = 1
✅ Correctly clamped to min.
-
Target is a float that results in a value above max:
target = 2.0
process_cpu_count() = 1000
val = int(1000 * 2.0) = 2000
result = max(2000, min=1) = 2000
result = min(2000, max=1024) = 1024
✅ Correctly clamped to max.
-
Target is an integer outside the [min, max] range:
target = 0
min = 1
max = 1024
val = 0
result = max(0, 1) = 1
result = min(1, 1024) = 1
✅ Clamped correctly.
Conclusion
The min/max clamping logic in the calc_num_workers function is correct and well-designed. It ensures that the computed number of workers is always within the specified range, regardless of whether the target is an integer or float, and even if the computation yields values outside the bounds of min and max. The order of operations (max followed by min) is appropriate and avoids any potential issues with incorrect clamping.