简体   繁体   中英

The opposite of functools.partial

There is a library function that takes a callback and calls it with some 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. It results in "invalid argument count" error, so I have to wrap my callback with a lambda to ignore the argument:

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. 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?

Why doesn't your nullary_callback simply have a parameter you don't use? 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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