When you invoke a function with the wrong number of arguments, or with a keyword argument that isn't in its definition, you get a TypeError. I'd like a piece of code to take a callback and invoke it with variable arguments, based on what the callback supports. One way of doing it would be to, for a callback cb
, use cb.__code__.cb_argcount
and cb.__code__.co_varnames
, but I would rather abstract that into something like apply
, but that only applies the arguments which "fit".
For example:
def foo(x,y,z):
pass
cleanvoke(foo, 1) # should call foo(1, None, None)
cleanvoke(foo, y=2) # should call foo(None, 2, None)
cleanvoke(foo, 1,2,3,4,5) # should call foo(1, 2, 3)
# etc.
Is there anything like this already in Python, or is it something I should write from scratch?