Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check for valid arguments

Tags:

python

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.

Example

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
like image 723
Aaron Yodaiken Avatar asked Jan 29 '11 04:01

Aaron Yodaiken


People also ask

How do you prove an argument is invalid?

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?

How do you know if an argument is valid or invalid in math?

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.


1 Answers

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.
like image 109
Jason LeBrun Avatar answered Sep 28 '22 07:09

Jason LeBrun