I have a function in python similar to the following:
def checkargs(*args):
if len(args) == 1:
x = args
y = something
elif len(args) == 2:
x, y = args
return x, y
When I put in only one argument (a string), x comes out as a tuple. When I put in two arguments (two strings), x and y are returned as strings. How can I get x to come out as string if I only put in one argument?
This happens because args
is always a tuple, even if you only put in one argument. So, when you do:
x = args
This is like doing:
x = ('abc',)
There are two (equivalent) ways to fix this: either explicitly assign x
to the first element of the tuple:
x = args[0]
or invoke the same tuple unpacking that the x,y
assignment uses by assigning to a length-1 tuple:
x, = args
This should work:
def checkargs(*args):
try:
x, y = args
except ValueError:
(x,), y = args, 'something'
return x, y
However, if you are going to check for the presence of y
and assign it to a default something
when it's not there, consider redesigning the interface to simply use a default kwarg instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With