Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop function parameters for sanity check

I have a Python function in which I am doing some sanitisation of the input parameters:

def func(param1, param2, param3):
    param1 = param1 or ''
    param2 = param2 or ''
    param3 = param3 or ''

This caters for the arguments being passed as None rather than empty strings. Is there an easier/more concise way to loop round the function parameters to apply such an expression to all of them. My actual function has nine parameters.

like image 879
Mat Avatar asked Nov 26 '25 10:11

Mat


1 Answers

This looks like a good job for a decorator. How about this:

def sanitized(func):
    def sfunc(*args, **kwds):
        return func(*[arg or '' for arg in args],
                    **dict((k, v or '') for k,v in kwds.iteritems()))
    sfunc.func_name = func.func_name
    sfunc.func_doc = func.func_doc
    return sfunc

You would use this on your function like so:

@sanitized
def func(param1, param2, param3):
    print param1, param2, param3

Then the parameters will be replaced by the empty string if they are false:

>>> func('foo', None, 'spam')
foo  spam

(Note that this will still mess up the function signature as Ned Batchelder points out in his answer. To fix that you could use Michele Simionato's decorator module-- I think you'd just need to add a @decorator before the definition of sanitized)

like image 111
dF. Avatar answered Nov 27 '25 23:11

dF.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!