Search code examples
pythonfunctionchaining

How do you chain multiple functions, and return multiple tuples from each one?


I'm trying to write a program that contains numerous functions for different calculations, all of them involving tuples, and being controlled by a main()

the functions are essentially this:

def open_file()
def read_file()
def get_data()
def calculate_info()
def display_info()

def main()
    open_file()
    read_file()
    get_data()
    calculate_info()
    display_info()

main()

What confuses me is how to chain them together. For example, I want the read_file() to read what open_file() returned, get_data() to get what I want from what read_file() returned, etc.

My question is then what should actually be returned and how do I make sure the next function uses what the previous one returned? Related to that, what goes in the parentheses?


Solution

  • You can use something like this to process tuples in python

    def open_file(*file):
        return ("test", "test2")
    
    def read_file(*file):
        return ("test", "test2") 
    
    def get_data(data1, data2):
        return ("test", "test2")
    
    def calculate_info(*data):
        return (8, 10, 14)
    
    def display_info(*data):
        print data
    
    def main()
        (k,l) = open_file()
        (m,n) = read_file(k,l)
        (o,p) = get_data(m,n)
        (q,r,s) = calculate_info(o,p)
        display_info(q,r,s)
    
    main()
    

    You use the * operator to specify a tuple as a parameter in python. When returning return a tuple, and keep them either as a single variable like x = open_file()

    or (p,q) = open_file()