0

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?

  • `lambda` doesn't have that connotation in Python. Its main purpose is to create anonymous callables that can be passed as arguments without the need to bind a more permanent name with a `def` statement. – chepner Nov 29 '14 at 15:54
  • @chepner if that is their purpose then they are doing a poor job of it. You can´t define them with one or more statements, only a single expression. That´s what´s giving me the feeling that they are mainly callable wrappers for expressions. – MikkelBybjerg Jan 02 '15 at 20:42

1 Answers1

1

Use *args:

def handler(*args):
    #react

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

Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677