Suppose I have a very simple function:
def myFunction(arg1, arg2):
return arg1, arg2
Now if I only want to access the second argument, can do I something like:
none, arg2 = myFunction(arg1, arg2)
?
Suppose I have a very simple function:
def myFunction(arg1, arg2):
return arg1, arg2
Now if I only want to access the second argument, can do I something like:
none, arg2 = myFunction(arg1, arg2)
?
Yes, yes you can do something like that. Exactly that, actually.
Assign the argument you want to ignore to a name you then simply not use anywhere else. The _
name is often used:
_, arg2 = myFunction(arg1, arg2)
The _
name is just a convention, but most Python developers understand it to mean 'this variable will be ignored by the rest of the code, it is just there to fulfill a tuple assignment'.
Alternatively, index or slice the output:
arg2 = myFunction(arg1, arg2)[-1]
or for a function with more than two return values:
arg2, arg3 = returnsMoreThanTwo(arg1, arg2)[-2:]
but if you wanted to ignore an argument in the middle somewhere, the _
assignment is best. You can use it multiple times without penalty:
arg1, _, _, arg4 = returnsFourArguments(arg1, arg2)