Reputation: 150
I have a function with a definite set of arguments, but that during development the amount of arguments it recieves could change. Each argument can either be a string, or a list. I want to someway loop trough the arguments of the function, and if they are a string, convert them to a list with that single element.
I tried using locals()
to be able to loop trough the arguments, but I don't know how to modify the value during the iteration, so I guess that's not the correct approach:
def function(a, b, c, d):
for key in locals():
if type(key) == str:
# ??? key = list(locals[key])
# ... more code over here, assuming that a,b,c,d are lists
What's the correct way to acomplish this?
Thanks!
Upvotes: 1
Views: 1456
Reputation: 52191
You can use isinstance(key, str)
to check if a variable is a str or not
def function(a, b, c, d):
l= locals()
for i in l:
key = l[i]
if isinstance(key, str):
l[i] = [l[i]]
l = l.values()
print (l)
function('one', 'two', ['bla','bla'], ['ble'])
If you want list, then you need to have a line
l = l.values()
This will be
[['a'], ['c'], ['b'], ['d']]
EDIT: As you have suggested, the correct program is
def function(a, b, c, d):
l= locals()
dirty= False
for i in l:
key = l[i]
if isinstance(key, str):
l[i] = [l[i]]
dirty= True
if dirty:
function(**l)
else:
print a, b, c, d
print (l)
function('one', 'two', ['bla','bla'], ['ble'])
This will output
['one'], ['bla', 'bla'], ['two'], ['ble']
Upvotes: 1
Reputation: 3069
def function(*args):
arg_list = list(args)
for i in range(len(arg_list)):
if type(arg_list[i]) == str:
#Do the stuff
elif type(arg_list[i]) == list:
#Do the stuff
else:
#Do the stuff
function ('a','b', ['c', 'd', 'e'])
Upvotes: 0
Reputation: 31349
Use *args
or **kwargs
:
def use_args(*args):
# covert strings to `list` containing them
new_args = map(lambda x: [x] if isinstance(x, str) else x, args)
return new_args
print use_args([1, 2], "3")
Output:
[[1, 2], ['3']]
Upvotes: 1