I have a function in Python that takes a callback. This callback may take an parameter, but also may not. I want to call it in a uniform way.
In the (almost) simplest case (not the real case but abstracting the case will simpler the question), it'll looks like:
def wait_and_pass_square(callback, parameter):
from time import sleep
sleep(1000)
callback(parameter * parameter)
# Here's the problem - the callback may have the form:
# def callback(square):
# or the form:
# def callback():
# (without argument).
Now, if I choose one of the forms in the caller, the second form will trigger TypeError
.
I know that I can check for an exception and work-around it:
def wait_and_pass_square(callback, parameter):
from time import sleep
sleep(1000)
try:
callback(parameter * parameter)
except TypeError:
callback()
But I don't want to do it, because:
- It's ugly.
- It's become impossible when you have dozens of optional arguments (although that's not my problem, since my case is only one argument)
- It easy to make mistakes: for example, if the callback may throw a
TypeError
exception, it'll be caught incorrectly.
Another thing I can do is to change the callback, either to:
def callback(square=None):
Or to:
def callback(*args):
if 0 != len(args): square = args[0]
else: square = None
But I don't want to change the callback (because as it can be much more challenging, updating the library is one-time action versus updating the client code) and sometimes I can't even touch the client code.