MikkelBybjerg
MikkelBybjerg

Reputation: 59

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?

Upvotes: 0

Views: 190

Answers (1)

unutbu
unutbu

Reputation: 879361

Use *args:

def handler(*args):
    #react

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

Upvotes: 1

Related Questions