Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function returns tuple instead of string

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?

like image 505
dmb Avatar asked Mar 23 '23 21:03

dmb


2 Answers

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
like image 112
lvc Avatar answered Apr 01 '23 23:04

lvc


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.

like image 45
wim Avatar answered Apr 02 '23 00:04

wim