Reputation: 626
I have a library function that returns a tuple
and looks something like this
def some_function(some_string):
does something
return (text,id)
Now I want to pass the text returned from the some_function as argument to another function. The catch is the function has other arguments as well and I don't want to pass the entire tuple as a pointer. I also need need to retrieve many texts that will be generated by different values of some_string.
Depending on the condition met, I want to call another function which will look something like this
if abcd:
other_function(name,phone,**some_function("abcd")**,age)
elif xyz:
other_function(name,phone,**some_function("xyz")**,age)
else:
other_function(name,phone,**some_function("aaaa")**,age)
So what should I replace some_function("abcd") with so that it sends only the text and not both text and id as arguments?
The other_function is defined like this
def other_function(name,phone,text,age):
...
return
One solution that I came up with myself was to create another function that returns just the text.
def returntextonly(some_string):
self.some_string = some_string
(text,id) = some_function(some_string)
return text
and then call the other_function like
if abcd:
other_function(name,phone,returntextonly("abcd"),age)
I mostly program in C++ and have picked up python only recently. I was wondering if there is a better solution to the problem than creating a new function just to return one element of the tuple.
Thanks for reading.
Upvotes: 1
Views: 976
Reputation: 76837
You can run this as:
other_function(name, phone, some_function("abcd")[0], age)
There is no need to define the additional if
statements, wrapper functions etc, since you want to pass only the first element of the tuple which is returned from the original function.
For the general case, this becomes:
other_function(name, phone, some_function(some_string)[0], age)
Note that the tuple is another (immutable) iterator, and its elements can be accessed using the regular indexes like in lists.
Upvotes: 4