Skip to content

Commit 8748436

Browse files
committed
Fix parameter counting to exclude *args and **kwargs
The previous code was counting VAR_POSITIONAL (*args) and VAR_KEYWORD (**kwargs) parameters in the total count, which caused functions like 'lambda a, b, c, *args' to be counted as having 4 parameters instead of 3. Now only regular parameters are counted, while still checking for the presence of *args to allow variable argument functions. Also removed test_callable_fix.py as it was causing pytest errors. Signed-off-by: Samaresh Kumar Singh <ssam3003@gmail.com>
1 parent 5bf8fd3 commit 8748436

File tree

2 files changed

+11
-54
lines changed

2 files changed

+11
-54
lines changed

test_callable_fix.py

Lines changed: 0 additions & 46 deletions
This file was deleted.

tools/python/src/global_optimization.cpp

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -55,23 +55,26 @@ size_t num_function_arguments(py::object f, size_t expected_num)
5555
try {
5656
auto sig = inspect.attr("signature")(f);
5757
auto params = sig.attr("parameters");
58-
auto num = py::len(params);
5958

60-
// Check if function accepts *args (VAR_POSITIONAL)
59+
// Count only regular parameters, excluding VAR_POSITIONAL (*args) and VAR_KEYWORD (**kwargs)
60+
size_t num_regular_params = 0;
6161
bool has_var_args = false;
62+
6263
for (auto item : params.attr("values")()) {
6364
auto param = item.cast<py::object>();
64-
auto kind = param.attr("kind");
65-
// inspect.Parameter.VAR_POSITIONAL == 2
66-
if (kind.cast<int>() == 2) {
65+
auto kind = param.attr("kind").cast<int>();
66+
// inspect.Parameter.VAR_POSITIONAL == 2, VAR_KEYWORD == 4
67+
if (kind == 2) {
6768
has_var_args = true;
68-
break;
69+
} else if (kind != 4) {
70+
// Count all parameters except VAR_POSITIONAL and VAR_KEYWORD
71+
num_regular_params++;
6972
}
7073
}
7174

72-
if (num < expected_num && has_var_args)
75+
if (num_regular_params < expected_num && has_var_args)
7376
return expected_num;
74-
return num;
77+
return num_regular_params;
7578
} catch (const py::error_already_set&) {
7679
// Fallback to old method if inspect.signature fails
7780
// This maintains backward compatibility

0 commit comments

Comments
 (0)