1

I have a function like as below

def fun1():                 
  do something
  ....
  return df1,df2

def fun2(df1,df2):
  ...
  df3 = df1.merge(df2)
  do something
  return df3   

funcs = [fun1, fun2]
op_data = []
for func in funcs:
    op_data = func(*op_data)

But the above works, if I wish to return only df3. It goes and neatly gets stored in op_data.

However, what if I want to return df1,df2 and df3 from fun2.

I wish to access all df1,df2 and df3 after function execution. Currently am able to access only df3. but how can I access df1 and df2 the same way?

The Great
  • 7,215
  • 7
  • 40
  • 128
  • 1
    Why not use `return df1, df2, df3` in `fun2`? – Shaido Oct 04 '21 at 03:10
  • yes Shaido. If I return df1,df2 and df3 where will they get stored? – The Great Oct 04 '21 at 03:12
  • 1
    will all of them get stored in op-data? and how to access the, – The Great Oct 04 '21 at 03:12
  • 1
    Yes, op_data will be a tuple with the 3 dataframes. It's the same logic as when you return `df1, df2` from `fun1`. – Shaido Oct 04 '21 at 03:14
  • Hi Shaido, if I do that, I encounter the below issue.. https://stackoverflow.com/questions/69388680/unable-to-convert-bigdata-tuple-to-dataframe-using-pandas – The Great Oct 04 '21 at 03:15
  • Additionally, may I also check why is `op_data` a tuple, instead of a list? because I have defined op_data as a list initially? – The Great Oct 04 '21 at 03:20
  • hi @TheGreat. You can return return df1, df2, df3 as suggested. If you want it to be a list, after return, you can use list() to convert to list. then add to op_data – EBDS Oct 04 '21 at 03:27
  • `op_data` will be overwritten in each iteration of the loop (so whether you initialize it or not, the result will be the same). When returning multiple objects from a function these will be returned as a tuple by default (see e.g.: https://stackoverflow.com/questions/39345995/how-does-python-return-multiple-values-from-a-function/39346392). – Shaido Oct 04 '21 at 03:27
  • thanks for your help. Understood, If it can be written as an answer, I would be happy to mark and upvoted it – The Great Oct 04 '21 at 04:09
  • return df1, df2, df3. ### for func in funcs: op_data += list(func(*op_data)) ### issues is that there is an error when you call func with *list. I normally see the parameters given to a function as dict. Assuming that part is solved, then return df1, df2, df3 and use list() around the return tuple will convert to a list. – EBDS Oct 04 '21 at 04:52

1 Answers1

1

I just give this a try... ;-)

def fun1(*args):                 
    df1 = args[0]
    df2 = args[1]
    return df1,df2

def fun2(*args):
    df1 = args[0]
    df2 = args[1]
    df3 = df1.merge(df2)
    return df1, df2, df3

funcs = [fun1, fun2]
op_data = [df1,df2]
for func in funcs:
    op_data += list(func(*op_data))
EBDS
  • 1,244
  • 5
  • 16