使用functools.partial将其设置为值后,删除函数参数

joh*_*tis 6 python lambda function-signature functools

我想使用functools.partial将某个参数设置为常量,同时完全删除该参数。

让我用一个简单的例子来解释它。

from functools import partial
def f(a, b):
    return a * b

g = partial(f, b=2)
Run Code Online (Sandbox Code Playgroud)

但是,此函数g仍然具有以下调用签名:

g?

Signature:      g(a, *, b=1)
Call signature: g(*args, **kwargs)
Type:           partial
String form:    functools.partial(<function f at 0x7ff7045289d8>, b=1)
File:           /opt/conda/envs/dev/lib/python3.6/functools.py
Docstring:     
partial(func, *args, **keywords) - new function with partial application
of the given arguments and keywords.
Run Code Online (Sandbox Code Playgroud)

我当然可以使用lambda函数来做到这一点,例如:

def f(a, b):
    return a * b

g = lambda a: f(a, b=2)
Run Code Online (Sandbox Code Playgroud)

具有正确的呼叫签名:

g?

Signature: g(a)
Docstring: <no docstring>
File:      ~/Work/<ipython-input-7-fc5f3f492590>
Type:      function
Run Code Online (Sandbox Code Playgroud)

使用lamdba函数的缺点是我需要再次写下所有参数。在我的简单示例中,这无关紧要,但是请看以下内容:

phase_func = lambda site1, site2, B_x, B_y, B_z, orbital, e, hbar: \
    phase_func(site1, site2, B_x, B_y, B_z, orbital, e, hbar, xyz_offset=(0,0,0))
# or this
phase_func = partial(phase_func, xyz_offset=(0,0,0)
Run Code Online (Sandbox Code Playgroud)

我为什么还要这个?

稍后在我的代码中,我使用包装器,这些包装器可以通过将两个其他函数相乘生成一个新函数,例如combine(function1, function2, operator.mul)。此combine函数查看所有参数,因此我需要在设置参数后将其删除。