I have a Python function accepting several string arguments def foo(a, b, c):
and concatenating them in a string.
I want to iterate over all function arguments to check they are not None. How it can be done?
Is there a quick way to convert None to ""?
Thanks.
You can use the inspect module and define a function like that:
in argspec there are all the info you need to perform any operation with argument passed.
To concatenate the string is sufficient to use the arg info received:
For reference: http://docs.python.org/library/inspect.html#inspect.getargvalues
Is this perhaps what you'd like?
Notice the use of vars(), which returns a dict.
locals()
may be your friend here if you call it first thing in your function.Example 1:
Example 2:
Answer:
Update:
'Example 1' highlights that we may have some extra work to do if the order of your arguments is important as the
dict
returned bylocals()
(orvars()
) is unordered. The function above also doesn't deal with numbers very gracefully. So here are a couple of refinements:if you're joining on an empty string, you could just do
''.join(i for i in args if i is not None)
I would use sed s/None//g, but that's not in python, but you can probably use os.popen() to do that.