简体   繁体   English

functools.partial 的反面

[英]The opposite of functools.partial

There is a library function that takes a callback and calls it with some arguments:有一个库 function 接受回调并使用一些 arguments 调用它:

def library_function(callback):
    # crunching numbers
    callback(result)

I don't need the result but I still want to handle the fact that the library function has finished, so I pass a nullary function as a callback.我不需要结果,但我仍然想处理库 function 已经完成的事实,所以我将一个无效的 function 作为回调传递。 It results in "invalid argument count" error, so I have to wrap my callback with a lambda to ignore the argument:它会导致“无效参数计数”错误,所以我必须用 lambda 包装我的回调以忽略该参数:

def nullary_callback():
    print("Handled!")

library_function(lambda x: nullary_callback())

functools.partial does the opposite task: binding a certain argument and reducing the arity of the function. functools.partial执行相反的任务:绑定某个参数并减少 function 的数量。 Is there any standard helper that increases the arity ignoring newly added arguments, so I can replace my lambda with it, or my approach is already pythonic enough?是否有任何标准助手可以增加忽略新添加的 arguments 的数量,所以我可以用它替换我的 lambda,或者我的方法已经足够pythonic了?

Why doesn't your nullary_callback simply have a parameter you don't use?为什么你的nullary_callback没有一个你不使用的参数? That would make it a valid callback for where you're using it.这将使它成为您使用它的有效回调。

If you need a generic callback that always works (because it never does anything):如果您需要一个始终有效的通用回调(因为它从不做任何事情):

def nullary_callback(*args, **kwargs):
    print("Handled!")


library_function(nullary_callback)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM