Python partial 对应忽略参数
Python counterpart to partial for ignoring an argument
在 python 中是否有 functools.partial
的 "counterpart"?
即我要避免的是写:
lambda x, y: f(x)
但我希望保留与我编写时相同的属性(关键字参数,漂亮的 repr):
from functools import partial
incr = partial(sum, 1)
而不是
incr = lambda x: sum(1, x)
我知道像这样的东西很容易写,但我想知道是否已经有忽略参数的标准方法。
一个常见的用例是 Qts 信号和插槽。
只需编写一个装饰器,从调用中删除一定数量的参数:
def ignoreargs(func, count):
@functools.wraps(func)
def newfunc(*args, **kwargs):
return func(*(args[count:]), **kwargs)
return newfunc
>>> def test(a, b):
print(a, b)
>>> test3 = ignoreargs(test, 3)
>>> test3(1, 2, 3, 4, 5)
4 5
my basic idea would be to make it more generic by default, e.g. having the signature: remap_args(f, mapping)
where mapping is an iterable of ints which give you the position of the argument of the created function.
def remap_args(func, mapping):
@functools.wraps(func)
def newfunc(*args, **kwargs):
newargs = [args[m] for m in mapping]
return func(*newargs, **kwargs)
return newfunc
>>> t = remap_args(test, [5, 2])
>>> t(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
5 2
在 python 中是否有 functools.partial
的 "counterpart"?
即我要避免的是写:
lambda x, y: f(x)
但我希望保留与我编写时相同的属性(关键字参数,漂亮的 repr):
from functools import partial
incr = partial(sum, 1)
而不是
incr = lambda x: sum(1, x)
我知道像这样的东西很容易写,但我想知道是否已经有忽略参数的标准方法。
一个常见的用例是 Qts 信号和插槽。
只需编写一个装饰器,从调用中删除一定数量的参数:
def ignoreargs(func, count):
@functools.wraps(func)
def newfunc(*args, **kwargs):
return func(*(args[count:]), **kwargs)
return newfunc
>>> def test(a, b):
print(a, b)
>>> test3 = ignoreargs(test, 3)
>>> test3(1, 2, 3, 4, 5)
4 5
my basic idea would be to make it more generic by default, e.g. having the signature:
remap_args(f, mapping)
where mapping is an iterable of ints which give you the position of the argument of the created function.
def remap_args(func, mapping):
@functools.wraps(func)
def newfunc(*args, **kwargs):
newargs = [args[m] for m in mapping]
return func(*newargs, **kwargs)
return newfunc
>>> t = remap_args(test, [5, 2])
>>> t(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
5 2