Search code examples
pythonargument-passingfunction-calls

Pass function outputs as arguments to another function


I need to pass the output of a function in Python as an argument to another function. The only catch is that the 1st function returns a tuple and the entire tuple needs to be passed to the second function.

For ex:

I have a library function:

def some_function(some_string, some_number):
    # does something
    return (text,id)

Now I want to pass text and id returned from the some_function as arguments to another function. The catch is that the function has other arguments as well. I also need need to retrieve many texts and ids that will be generated by different values of some_string and number.

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","123")**,age)
 elif xyz:
     other_function(name,phone,**some_function("xyz","911")**,age)
 else:
     other_function(name,phone,**some_function("aaaa","000")**,age)

So what should I replace some_function("abcd","123") with so that it expands the tuple and sends both the text and id as arguments?

The other_function is defined like this

def other_function(name, phone, text, id, age):
   ...
    return 

Will simply passing some_function("aaaa","000") as an argument work?


I am asking this because I wrote a simple code to test my hypothesis and it was giving me a blank output.

def f(id,string):
    return ("123", "hello")

def a(name, age, id, words, phone):
     print name + age + id + words + phone


def main():
    a("piyush", "23", f("12", "abc"), "123")

Solution

  • You could also change the order of arguments in the signature:

    def a(name, age, id, words, phone):
         name = name
         age=age
         id=id
         words=words
         phone=phone
         print name+age+id+words+phone
    
    a("piyush", "23", 123, *f("12","123"))
    piyush23123123hello
    

    This way you can unpack the returned values directly when calling the function. Note, however, that this makes readability very poor and debugging harder.

    Also if you don't want to use unpacking and change the you call your function you can change the code like this:

    def a(name, age, id_words, phone):
         name = name
         age=age
         id=id_words[0]
         words=id_words[1]
         phone=phone
         print name+age+id+words+phone
    
    a("piyush", "23", f("12","123"), "123")
    piyush23123hello123
    

    This has the advatage of keeping all the functions call the same as they were. Only the interal works of the function change, not the signature.