【问题标题】:How to tell a function to use the default argument values?如何告诉函数使用默认参数值?
【发布时间】:2019-08-25 03:22:57
【问题描述】:

我有一个函数foo 调用math.isclose:

import math
def foo(..., rtol=None, atol=None):
    ...
    if math.isclose(x, y, rel_tol=rtol, abs_tol=atol):
        ...
    ...

如果我没有将rtol 和atol 传递给foo,上述操作在math.isclose 中失败:

TypeError: must be real number, not NoneType

我不想将系统默认参数值放在我的代码中(什么 如果他们改变了?)

这是我到目前为止的想法:

import math
def foo(..., rtol=None, atol=None):
    ...
    tols = {}
    if rtol is not None:
        tols["rel_tol"] = rtol
    if atol is not None:
        tols["abs_tol"] = atol
    if math.isclose(x, y, **tols):
        ...
    ...

这看起来又长又傻,每次调用时都会分配一个dict foo(递归调用自身,所以这很重要)。

那么,告诉math.isclose 使用默认值的最佳方法是什么 公差?

PS。有几个相关的问题。请注意,我确实不想知道math.isclose 的实际默认参数——我只想告诉它使用默认值。

【问题讨论】:

  • 您可以获取默认参数的值:Get a function argument's default value? 并想出一种使用这些值定义函数的方法。可能有一种方法可以使用functools.partial
  • stackoverflow.com/questions/4670665/… 的可能重复项,但您不会在其中找到更好的答案。
  • @pault 我试过inspect.signature(math.isclose),但它失败了ValueError: no signature found for builtin <built-in function isclose>。
  • @Sanyash 它在 python 3.7.2 中对我有用。
  • @Aran-Fey 确实,在 3.7.2 中有效,但在 3.6.6 中无效

标签: python python-3.x


【解决方案1】:

一种方法是使用可变参数解包:

def foo(..., **kwargs):
    ...
    if math.isclose(x, y, **kwargs):
        ...

这将允许您将atol 和rtol 指定为主函数foo 的关键字参数,然后它将原样传递给math.isclose。

但是,我还要说,传递给kwargs 的参数以某种方式修改函数的行为,而不是仅仅传递给被调用的子函数,这是惯用的。因此,我建议取而代之的是,命名一个参数,以便清楚地将其解包并原封不动地传递给子函数:

def foo(..., isclose_kwargs={}):
    ...
    if math.isclose(x, y, **isclose_kwargs):
        ...

您可以在 matplotlib 中看到等效模式(例如:plt.subplots - subplot_kw 和 gridspec_kw,所有其他关键字参数都作为 **fig_kw 传递给 Figure 构造函数)和 seaborn (例如:FacetGrid - subplot_kws、gridspec_kws)。

当有 多个 子函数您可能想要传递关键字参数但保留默认行为时,这一点尤其明显:

def foo(..., f1_kwargs={}, f2_kwargs={}, f3_kwargs={}):
    ...
    f1(**f1_kwargs)
    ...
    f2(**f2_kwargs)
    ...
    f3(**f3_kwargs)
    ...

警告:

注意default arguments are only instantiated once,所以你不应该在你的函数中修改空的dicts。如果需要,您应该改为使用 None 作为默认参数,并在每次运行函数时实例化一个新的空 dict:

def foo(..., isclose_kwargs=None):
    if isclose_kwargs is None:
        isclose_kwargs = {}
    ...
    if math.isclose(x, y, **isclose_kwargs):
        ...

我的偏好是在您知道自己在做什么的情况下避免这种情况,因为它更简短,而且通常我不喜欢重新绑定变量。但是,它绝对是一个有效的成语,而且它可以更安全。

【讨论】:

  • 进一步,记录 foo 的任何其他关键字参数都直接传递给math.isclose。
  • @chepner 是的,FacetGrid 示例就是这样做的。此外,我认为在传递关键字参数的情况下,明确的isclose_kwargs 或类似的参数将优于裸**kwargs。
  • 但是,不要使用可变的默认参数。 f1_kwargs=None 更好。
  • @gmds:我仍然可以使用foo.__defaults__[0]['bar'] = 42 来处理默认设置。并且函数的未来重构很容易错过您将这些定义为默认值。不要那么容易引入错误。
  • @MartijnPieters 任何知道以这种方式修改默认参数的人都可以用 Python 知道默认参数只实例化一次。至于其余的,同样,一个足够熟练的程序员会知道什么时候打破规则是有充分理由的——在这种情况下,就是简洁。我已经编辑了我的答案以注意默认参数陷阱,但我认为这就足够了。
【解决方案2】:

正确的解决方案是使用与math.isclose() 相同的默认值。无需对它们进行硬编码,因为您可以使用 inspect.signature() function 获得 当前 默认值:

import inspect
import math

_isclose_params = inspect.signature(math.isclose).parameters

def foo(..., rtol=_isclose_params['rel_tol'].default, atol=_isclose_params['abs_tol'].default):
    # ...

快速演示:

>>> import inspect
>>> import math
>>> params = inspect.signature(math.isclose).parameters
>>> params['rel_tol'].default
1e-09
>>> params['abs_tol'].default
0.0

这是因为math.isclose() 使用Argument Clinic tool 定义其参数:

[T]Argument Clinic 的最初动机是为 CPython 内置函数提供自省“签名”。过去,如果您传入内置函数,自省查询函数会抛出异常。有了 Argument Clinic,这已成为过去!

在底层,math.isclose() 签名实际上存储为字符串:

>>> math.isclose.__text_signature__
'($module, /, a, b, *, rel_tol=1e-09, abs_tol=0.0)'

这是由inspect 签名支持解析出来的,以便为您提供实际值。

并非所有 C 定义的函数都使用 Argument Clinic还,代码库将根据具体情况进行转换。 math.isclose() 是 converted for Python 3.7.0。

您可以使用 __doc__ 字符串作为备用字符串,因为在早期版本中,它也包含签名:

>>> import math
>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=6, micro=8, releaselevel='final', serial=0)
>>> math.isclose.__doc__.splitlines()[0]
'isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) -> bool'

所以更通用的后备可能是:

import inspect

def func_defaults(f):
    try:
        params = inspect.signature(f).parameters
    except ValueError:
        # parse out the signature from the docstring
        doc = f.__doc__
        first = doc and doc.splitlines()[0]
        if first is None or f.__name__ not in first or '(' not in first:
            return {}
        sig = inspect._signature_fromstr(inspect.Signature, math.isclose, first)
        params = sig.parameters
    return {
        name: p.default for name, p in params.items()
        if p.default is not inspect.Parameter.empty
    }

我认为这是一种权宜之计,只需要支持较旧的 Python 3.x 版本。该函数生成一个以参数名称为键的字典:

>>> import sys
>>> import math
>>> sys.version_info
sys.version_info(major=3, minor=6, micro=8, releaselevel='final', serial=0)
>>> func_defaults(math.isclose)
{'rel_tol': 1e-09, 'abs_tol': 0.0}

请注意,复制 Python 默认值的风险非常低;除非有错误,否则这些值不易更改。因此,另一种选择可能是将 3.5 / 3.6 已知默认值硬编码为后备,并使用 3.7 和更新版本中提供的签名:

try:
    # Get defaults through introspection in newer releases
    _isclose_params = inspect.signature(math.isclose).parameters
    _isclose_rel_tol = _isclose_params['rel_tol'].default
    _isclose_abs_tol = _isclose_params['abs_tol'].default
except ValueError:
    # Python 3.5 / 3.6 known defaults
    _isclose_rel_tol = 1e-09
    _isclose_abs_tol = 0.0

但请注意,您有更大的风险,不支持未来、其他参数和默认值。至少inspect.signature() 方法可以让您添加关于代码期望的参数数量的断言。

【讨论】:

  • inspect.signature(math.isclose) 在 Python 3.6 中不起作用
  • @sds:对,Argument Clinic 转换是在 3.7 中完成的。祝你好运!
  • 另外math.isclose.__text_signature__ 包含None 在 Python3.6.6 上为我服务。
  • @Sanyash:是的,这就是我的回答。它需要 3.7 或更高版本才能工作。
  • @MartijnPieters 我认为如果您在 this post 上添加通用后备选项会很有用。
【解决方案3】:

确实没有太多方法可以让函数使用其默认参数...您只有两个选择:

  1. 传递真正的默认值
  2. 根本不传递参数

由于没有一个选项很好,我将列出一个详尽的列表,以便您可以比较它们。

  • 使用**kwargs 传递参数

    使用**kwargs 定义您的方法并将其传递给math.isclose:

    def foo(..., **kwargs):
        ...
        if math.isclose(x, y, **kwargs):
    

    缺点:

    • 两个函数的参数名称必须匹配(例如foo(1, 2, rtol=3) 不起作用)
  • 手动构造一个**kwargs dict

    def foo(..., rtol=None, atol=None):
        ...
        kwargs = {}
        if rtol is not None:
            kwargs["rel_tol"] = rtol
        if atol is not None:
            kwargs["abs_tol"] = atol
        if math.isclose(x, y, **kwargs):
    

    缺点:

    • 丑陋,写代码很痛苦,而且速度不快
  • 硬编码默认值

    def foo(..., rtol=1e-09, atol=0.0):
        ...
        if math.isclose(x, y, rel_tol=rtol, abs_tol=atol):
    

    缺点:

    • 硬编码值
  • 使用自省查找默认值

    您可以使用inspect 模块在运行时确定默认值:

    import inspect, math
    
    signature = inspect.signature(math.isclose)
    DEFAULT_RTOL = signature.parameters['rel_tol'].default
    DEFAULT_ATOL = signature.parameters['abs_tol'].default
    
    def foo(..., rtol=DEFAULT_RTOL, atol=DEFAULT_ATOL):
        ...
        if math.isclose(x, y, rel_tol=rtol, abs_tol=atol):
    

    缺点:

【讨论】:

  • inspect.signature(math.isclose) 在 Python 3.6 中不起作用
【解决方案4】:

将递归委托给辅助函数,这样您只需构建一次dict。

import math
def foo_helper(..., **kwargs):
    ...
    if math.isclose(x, y, **kwargs):
        ...
    ...


def foo(..., rtol=None, atol=None):
    tols = {}
    if rtol is not None:
        tols["rel_tol"] = rtol
    if atol is not None:
        tols["abs_tol"] = atol

    return foo_helper(x, y, **tols)

或者,不是将公差传递给foo,而是传递一个已经包含所需公差的函数。

from functools import partial

# f can take a default value if there is a common set of tolerances
# to use.
def foo(x, y, f):
    ...
    if f(x,y):
        ...
    ...

# Use the defaults
foo(x, y, f=math.isclose)
# Use some other tolerances
foo(x, y, f=partial(math.isclose, rtol=my_rtel))
foo(x, y, f=partial(math.isclose, atol=my_atol))
foo(x, y, f=partial(math.isclose, rtol=my_rtel, atol=my_atol))

【讨论】:

    猜你喜欢
    • 2015-06-07
    • 2021-11-23
    • 2012-03-17
    • 2012-08-01
    • 2011-02-20
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多