0

Is it possible to have the below code without raising an exception?
The hello function represents code outside my control. It is only here for the sake of clarity.

def hello():
    print("hellowed")

def callsCallback(callback):
    callback(*["dd"])

callsCallback(hello)

The idea is for a library to receive a callback function for when something happens. For backwards compatibility, the function being called may or may not receive parameters.

I'm aware of this answer: How can I find the number of arguments of a Python function? but I'd rather avoid inspection, if I can.

brunoais
  • 4,743
  • 7
  • 33
  • 55

1 Answers1

0

If you used *args in a wrapper function then it would never throw an exception because of the incorrect number of arguments.

def hello():
    print("hellowed")

def wrapper(f):
    def g(*args):
        f() 
    return g

def callsCallback(callback):
    callback = wrapper(callback)
    callback(*["dd"])

callsCallback(hello)

You could use a decorator style function. This may be overkill for what you want to do.

If you don't know ahead of time how many arguments hello takes, you would have to introspect as you suggested to call the function appropriately.

kdheepak
  • 1,079
  • 7
  • 20