简体   繁体   中英

Python wrapper function discarding arguments

I have a setting where event handlers are always functions taking a single event argument.

But more often than not, I find myself writing handlers that doesn´t use any of the event information. So I constantly write handlers of the form:

def handler(_):
    #react

In order to discard the argument.

But I wish I didn´t have to, as sometimes I want to reuse handlers as general action functions that take no arguments, and sometimes I have existing zero-arguments functions that I want to use as handlers.

My current solution is wrapping the function using a lambda:

def handler():
    #react

event.addHandler(lambda _:handler())

But that seems wrong for other reasons.

My intuitive understanding of a lambda is that it is first and foremost a description of a return value, and event handlers return nothing. I feel lambdas are meant to express pure functions, and here I´m using them only to cause side effects.

Another solution would be a general decorator discarding all arguments.

def discardArgs(func):
    def f(*args):
        return func()
    return f

But I need this in a great many places, and it seems silly having to import such a utility to every script for something so simple.

Is there a particularly standard or "pythonic" way of wrapping a function to discard all arguments?

Use *args :

def handler(*args):
    #react

Then handler can take 0 arguments, or any number of position arguments.

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