-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Description
Is your feature request related to a problem? Please describe.
The approx_fprime
function in scipy.optimize
currently does not support keyword arguments (kwargs
) for the objective function f
. This limitation can lead to errors or warnings when f
is a keyword-only function, as described in PEP 3102.
PEP 3102 introduces the concept of keyword-only arguments in Python, where arguments can be passed only by keyword and not by position. This is increasingly used in modern Python code to improve clarity and prevent errors. However, when such a function is passed to approx_fprime
, it results in errors because approx_fprime
only supports positional arguments through *args
.
Describe the solution you'd like.
Enhance approx_fprime
to accept kwargs
and pass them to the objective function f
. This would align approx_fprime
with modern Python practices, reduce potential errors, and improve its flexibility.
The updated signature could look like this:
def approx_fprime(xk, f, epsilon=_epsilon, *args, **kwargs):
...
Describe alternatives you've considered.
Example of the Issue
Consider a function that requires keyword-only arguments:
import numpy as np
from scipy.optimize import approx_fprime
def func_with_kwargs(x, *, a=1.0, b=2.0):
return a * np.sum(x**2) + b
xk = np.array([1.0, 2.0, 3.0])
epsilon = 1e-8
# This will raise an error because approx_fprime does not support kwargs
grad = approx_fprime(xk, func_with_kwargs, epsilon, 1.0, 2.0)
In this case, func_with_kwargs
cannot be passed to approx_fprime
without a workaround, such as wrapping it in another function or using functools.partial
, both of which add unnecessary complexity.
Additional context (e.g. screenshots, GIFs)
Benefits
-
Compatibility with Modern Python Code: By supporting
kwargs
,approx_fprime
would be compatible with functions that utilize keyword-only arguments, as per PEP 3102. -
Ease of Use: Users would no longer need to resort to workarounds like wrappers or
functools.partial
to pass keyword arguments, making the function easier to use in a broader range of scenarios. -
Backward Compatibility: The proposed change is backward-compatible, as it would not affect existing code that only uses positional arguments.
Conclusion
Supporting kwargs
in approx_fprime
would make the function more versatile, aligning it with modern Python practices and improving its usability. This enhancement would be particularly beneficial for users working with keyword-only functions, which are becoming more common in the Python ecosystem.