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.


Asked by: John871 | Posted: 30-11-2021






Answer 1

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)

Answered by: Lucas619 | Posted: 01-01-2022



Answer 2

You could do some list manipulation:

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

but I'm not sure that's better than just writing out the nine lines, since once you get to nine parameters, that's a heinously long line.

You could change the declaration of the function:

def func(*args):
    param1, param2, param3 = map(lambda x: x or '', args)

but then you lose the documentation that comes from having real parameter names, as well as the possibility of changing the defaults, etc. And you still have a pretty fugly line there to unpack them.

I say write out the nine lines, or change the function to have fewer parameters: nine is kind of a lot anyway!

Answered by: Brad466 | Posted: 01-01-2022



Answer 3

def func(x='', y='', z='hooray!'):
    print x, y, z

In [2]: f('test')
test  hooray!

In [3]: f('test', 'and')
test and hooray!

In [4]: f('test', 'and', 'done!')
test and done!

Answered by: Adrian622 | Posted: 01-01-2022



Similar questions

Print out list of function parameters in Python

Is there a way to print out a function's parameter list? For example: def func(a, b, c): pass print_func_parametes(func) Which will produce something like: ["a", "b", "c"]


Python - use list as function parameters

How can I use a Python list (e.g. params = ['a',3.4,None]) as parameters to a function, e.g.: def some_func(a_char,a_float,a_something): # do stuff


python - How to pass tuple as parameters of a function

I have a tuple containing tuples. EVENT_MAPPING = ( (func1, (paramA1, paramA2, paramA3)), (func2, (paramB1)), (func3, (paramC1, paramC2)), ) I iterate over the first tuple. And I want to call the function contained in the first param with args in the second param plus other param. For example, for the first tuple : func1(origin, paramA1, paramA2, paramA3)


How do I ask a function for the names of its parameters in Python?

This question already has answers here:


Function parameters - Python

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): print "-- This parrot wouldn’t", action print "if you put", voltage, "volts through it." print "-- Lovely plumage, the", type print "-- It’s", state, "!" I started learning python. I can call this function using parrot(5,'dead') and parrot(voltage=5). But why can't I call with the same function with parrot(...


Python / Function parameters

Main objective: function to read top score from text file. Parameters to be passed onto function: A text document! def highscore(): try: text_file = open ("topscore.txt", "r") topscore = int(text_file.read()) print topscore text_file.close() return topscore except: print "Error - no file" topscore = 0 return topscore ...


How to pass a list of parameters to a function in Python

I warped a class in this way: import Queue import threading class MyThread(): q = Queue.Queue() content = [] result = {} t_num = 0 t_func = None def __init__ (self, t_num, content, t_func): for item in content: self.q.put(item) self.t_num = t_num self.t_func = t_func def start(self): for i in range(self.t_num): t = threadi...


how to print 3 parameters in a function in order in python


How do I pass parameters to a Python function?

I am trying to use this function found online to calculate the distance between two latitude and longitude points on the Earth. However, I do not know how to pass my values for latitude and longitude because I replace lat1, lon1 and lat2, lon2, and I get an error every time. Where do i put in the values I want for latitude and longitude? i...


order of parameters of function call of python

Suppose I have a function with 10 args: def foo(arg1,arg2,arg3,arg4.....): Sometimes, I need to call it with only arg1 and another time arg1, arg4, or arg4 , arg7. My program doesn't specify the type of the function call. Does python have a way to help me?


How can write a python function that takes two parameters one being a list

Closed. This question does not meet Stack Overflow guid...


python - Reduce function with three parameters

How does reduce function work in python3 with three parameters instead of two. So, for two, tup = (1,2,3) reduce(lambda x, y: x+y, tup) I get this one. This would just sum up all the elements in tup. However, if you give reduce function three parameters like this below, tup = (1,2,3) reduce(lambda x, y: x+y, tup, 6) this would giv...


python - Can I split an array out of function parameters

Given a fixed length list and a function l = [1, 2, 3, 4, 5] def printMiddle(first, middle, last): print middle printMiddle(*l) How do I force middle to print l[1:3] with the output below? [2, 3, 4]


python - How to enter parameters to function in form of a list or a tuple?

Is it possible to enter the parameters of function in form of a list. For example - list1 = ["somethin","some"] def paths(list): import os path = os.path.join() #I want to enter the parameters of this function from the list1 return path Okay i got my answer but just an aditional question, related to this only - here is my code - def files_check(file_name,sub_...


Parameters of a function in python

I have the code below and I would like to feel the parameters of the function map at runtime. It should be like #devices = map(InputDevice, ('/dev/input/event15','/dev/input/event16')) But when I try to do it at runtime, it does not work. Here is my attempt: readers = "" devices = map(InputDevice, list_devices()) for dev in devices: if "深" in dev.name or "Barcode" in d...


python - Issue with equal signs and function parameters

I'm trying to build a function that would allow to repeat this (it prevents the console from opening in windows): if platform.system() == 'Windows': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW subprocess.call(['myprogram.exe', '-P', arg], stdout=someFile, startupinfo=startupinfo) else: subprocess.c...


python - Create a function that looks at three parameters type

I want to create a function that looks at three parameters and if they are all of the same type to return a boolean True value otherwise false : This is what I have so far: def whattype(n): if type(n) is int: print "True" elif type(n) != int: print "False" whattype("car") whattype(1) whattype(2)


python - Can I use a function passed by parameters?

I have a function, and inside this function I should execute another function of 3 posibilities. The simple way should be passing a parameter, doing a if-elif to exec function acording to that parameter, but I'd like to know it it's posible to pass the name of a funtion by params and use that, something like: FunctionA(Param1, Param2, FunctionNameToUse) ....Code.... FunctionNameToUse(Value1,...


python - How to get parameters from root function

I have the code below: from flask import Flask app = Flask(__name__) @app.route("/<param1>", methods=["GET"]) def func1(param1): return func2() def func2(): return "mystring" if __name__ == "__main__": app.run(host="0.0.0.0", port=8080, debug=True) The question is how to pass param1 to func2 but not as a function parameter. In my project


python - Insert List of Parameters Function into DB

I use inspect module trying to insert a list of parameters of Python function into PostgreSQL DB. I managed to get thses parameters printed but not inserted into DB. I'm getting this error: ERROR: Mixing iteration and read methods would lose data Code: import inspect def func(a, b, c): frame = inspect.currentframe() args, _, _, values = inspect.getargvalues...


Print out list of function parameters in Python

Is there a way to print out a function's parameter list? For example: def func(a, b, c): pass print_func_parametes(func) Which will produce something like: ["a", "b", "c"]


Caching the results of a function with two parameters in Python

I have a method with two parameters that does some complex computation. It is called very often with the same parameters, so I am using a dictionary for caching. Currently this looks something like this: def foo(self, a, b): params = frozenset([a, b]) if not params in self._cache: self._cache[params] = self._calculate(a, b) return self._cache[params] The reason for buil...


python function that modifies parameters

def add(a,b): for i in range(len(a)): a[i] = a[i] + b def main(): amounts = [100,200] rate = 1 add(amounts,rate) print amounts main() The function add does not have a return. I read that changes are available to only mutable objects like list. But why did the person omits the return? Either with or without return is fine. Why? This is so different from C++. Th...


function - How to not specify default parameters in python?

I'm working with a python package (MySQLdb). The connect method has lots of positional parameters, most of which have defaults, but some aren't easy to deduce. How can I only specify the parameters I want? i.e. if a connect method has the following signature: connect(username, password, socket, timeout) and socket has a default value which may be system-depende...


Python - use list as function parameters

How can I use a Python list (e.g. params = ['a',3.4,None]) as parameters to a function, e.g.: def some_func(a_char,a_float,a_something): # do stuff


plot - Python Subplot function parameters

I am having a hard time with putting in the parameters for the python subplot function. What I want is to plot 4 graphs on a same image file with the following criteria left space right space left space right I have tried different ways of the 3 numbers but the output doesnt show up correctly.


How does a lambda function refer to its parameters in python?

I am new in Python. My task was quite simple -- I need a list of functions that I can use to do things in batch. So I toyed it with some examples like fs = [lambda x: x + i for i in xrange(10)] Surprisingly, the call of [f(0) for f in fs] gave me the result like [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]. It was not what I expected as I'd like the variab...


Finding python function parameters from C++

I am calling python functions from C++. I was wondering if it is possible to determine the number of parameters and the names of these parameters. I have read the link How to find the number of parameters to a Python function from C? however I do not really understand. I have this C++ function ...


python - How to pass tuple as parameters of a function

I have a tuple containing tuples. EVENT_MAPPING = ( (func1, (paramA1, paramA2, paramA3)), (func2, (paramB1)), (func3, (paramC1, paramC2)), ) I iterate over the first tuple. And I want to call the function contained in the first param with args in the second param plus other param. For example, for the first tuple : func1(origin, paramA1, paramA2, paramA3)


python - How to change function parameters during runtime?

I'm a beginner and use Python 2.7. I want to make the definitions parameters to be changeable so I can controll the pause and string output on the fly. Is this possible? I've read some thread stuff but it seems to be more about executing two tasks at the same time. I want communication between the two tasks during runtime. def writeAndPause(stringToWrite,pauseSeconds) while True: pr...


python - Django: Arbitrary number of unnamed urls.py parameters

I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this: /browse/<name1>/<value1>/<name2>/<value2>/ .... etc .... where 'name' maps to a model attribute and 'value' is the search criteria for that...


python - variables as parameters in field options

I want to create a model, that will set editable=False on creation, and editable=True on editing item. I thought it should be something like this: home = models.ForeignKey(Team, editable=lambda self: True if self.id else False) But it doesn't work. Maybe something with overriding the init can help me, but i don't sure what can do the trick. I know i can check for self.id...


c# - How to analyse .exe parameters inside the program?

I have a program that can have a lot of parameters (we have over +30 differents options). Example: myProgram.exe -t alpha 1 -prod 1 2 -sleep 200 This is 3 Commands (from command pattern object at the end) that each contain some parameters. Inside the code we parse all command (start with -) and get a list of string (split all space) for the parameters. So in fact, we have : string-->Collection ...


python - Default parameters to actions with Django

Is there a way to have a default parameter passed to a action in the case where the regex didnt match anything using django? urlpatterns = patterns('',(r'^test/(?P<name>.*)?$','myview.displayName')) #myview.py def displayName(request,name): # write name to response or something I have tried setting the third parameter in the urlpatterns to a dictionary containing ' and giving...


python - How can I pass all the parameters to a decorator?

I tried to trace the execution of some methods using a decorator. Here is the decorator code: def trace(func): def ofunc(*args): func_name = func.__name__ xargs = args print "entering %s with args %s" % (func_name,xargs) ret_val = func(args) print "return value %s" % ret_val print "exiting %s" % (func_nam...


parameters - Python Newbie: Returning Multiple Int/String Results in Python

I have a function that has several outputs, all of which "native", i.e. integers and strings. For example, let's say I have a function that analyzes a string, and finds both the number of words and the average length of a word. In C/C++ I would use @ to pass 2 parameters to the function. In Python I'm not sure what's the right solution, because integers and strings are not passed by reference but by value (at leas...


Print out list of function parameters in Python

Is there a way to print out a function's parameter list? For example: def func(a, b, c): pass print_func_parametes(func) Which will produce something like: ["a", "b", "c"]


python - How to create a decorator that can be used either with or without parameters?

I'd like to create a Python decorator that can be used either with parameters: @redirect_output("somewhere.log") def foo(): .... or without them (for instance to redirect the output to stderr by default): @redirect_output def foo(): .... Is that at all possible? Note that I'm not looking for a different solution to the problem of redirectin...


python - Scope of lambda functions and their parameters?

This question already has answers here:


sql - How do you make the Python Msqldb module use ? in stead of %s for query parameters?

MySqlDb is a fantastic Python module -- but one part is incredibly annoying. Query parameters look like this cursor.execute("select * from Books where isbn=%s", (isbn,)) whereas everywhere else in the known universe (oracle, sqlserver, access, sybase...) they look like this cursor.execute("select * from Books where isbn=?", (isbn,)) This means that if you ...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top