| 47 | } |
| 48 | |
| 49 | size_t num_function_arguments(py::object f, size_t expected_num) |
| 50 | { |
| 51 | // Use Python's inspect module to get signature, which works with all callable objects |
| 52 | // including functools.partial, lambdas, and regular functions |
| 53 | auto inspect = py::module_::import("inspect"); |
| 54 | |
| 55 | try { |
| 56 | auto sig = inspect.attr("signature")(f); |
| 57 | auto params = sig.attr("parameters"); |
| 58 | |
| 59 | // Count only regular parameters, excluding VAR_POSITIONAL (*args) and VAR_KEYWORD (**kwargs) |
| 60 | size_t num_regular_params = 0; |
| 61 | bool has_var_args = false; |
| 62 | |
| 63 | for (auto item : params.attr("values")()) { |
| 64 | auto param = item.cast<py::object>(); |
| 65 | auto kind = param.attr("kind").cast<int>(); |
| 66 | // inspect.Parameter.VAR_POSITIONAL == 2, VAR_KEYWORD == 4 |
| 67 | if (kind == 2) { |
| 68 | has_var_args = true; |
| 69 | } else if (kind != 4) { |
| 70 | // Count all parameters except VAR_POSITIONAL and VAR_KEYWORD |
| 71 | num_regular_params++; |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | if (num_regular_params < expected_num && has_var_args) |
| 76 | return expected_num; |
| 77 | return num_regular_params; |
| 78 | } catch (const py::error_already_set&) { |
| 79 | // Fallback to old method if inspect.signature fails |
| 80 | // This maintains backward compatibility |
| 81 | if (!hasattr(f, "__code__") && !hasattr(f, "func_code")) { |
| 82 | throw; |
| 83 | } |
| 84 | const auto code_object = f.attr(hasattr(f,"func_code") ? "func_code" : "__code__"); |
| 85 | const auto num = code_object.attr("co_argcount").cast<std::size_t>(); |
| 86 | if (num < expected_num && (code_object.attr("co_flags").cast<int>() & CO_VARARGS)) |
| 87 | return expected_num; |
| 88 | return num; |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | double call_func(py::object f, const matrix<double,0,1>& args) |
| 93 | { |