So let's define a few functions:
def x(a, b, c): pass
def y(a, b=1, c=2): pass
def z(a=1, b=2, c=3): pass
Now, what's the best way to, given a pointer to x
, y
, or z
(p
), a tuple of args (a
) and a dictionary of kwargs (k
), check to see if
p(*a, **kw)
would produce any exception regarding having not enough arguments or incorrect arguments, etc—without actually calling p(*a, **kw)
and then catching the exceptions raised.
def valid(ptr, args, kwargs): ... #implementation here
valid(x, ("hello", "goodbye", "what?"), {}) # => True
valid(x, ("hello", "goodbye"), {}) # => False
valid(y, ("hello", "goodbye", "what?"), {}) # => True
valid(y, (), {"a": "hello", "b": "goodbye", "c": "what"}) #=> True
valid(y, ("hello", "goodbye"), {"c": "what?"}) #=> True
An argument is invalid if the conclusion doesn't follow necessarily from the premises. Whether or not the premises are actually true is irrelevant. So is whether or not the conclusion is true. The only question that matters is this: Is it possible for the premises to be true and the conclusion false?
An argument is a set of initial statements, called premises, followed by a conclusion. An argument is valid if and only if in every case where all the premises are true, the conclusion is true. Otherwise, the argument is invalid.
You can use the inspect
module's getargspec
function to determine the functions of the arguments and their defaults, if any, as well as if the function accepts varargs or keywordargs. This should be enough information to determine if a given tuple will satisfy the argument requirements.
Here's a start (have to run, but I figured posting a start was better than nothing).
def valid(f, *args, **kwargs):
specs = getargspec(f)
required = specs.args[:-len(specs.defaults)] if (specs.defaults != None) else specs.args
#Now just check that your required arguments list is fulfilled by args and kwargs
#And check that no args are left over, unless the argspec has varargs or kwargs defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With