Home > database >  How to pass object across functions?
How to pass object across functions?

Time:02-16

learning and incorporating functions into a web-scraping project in python and ran into this problem. Basically I want to pass an object (pandas dataframe) to another function / across functions. Basically I want to pass y to out across functions: out.append(y).

def do_inner_thing(y):
    y = y   1
    out.append(y)
    
def do_outer_thing():
    out = []
    x = 2
    do_inner_thing(x)
    print(out)

do_outer_thing()

#Desired Output: 3

CodePudding user response:

You want a return statement - have the function return an object using statement of the same name. Also, variables inside functions are local, not global, so they can't be accessed from other functions. You'll need to pass your list as well. Something like:

def do_inner_thing(y, out):
    y = y   1
    out.append(y)
    return out
    
def do_outer_thing():
    out = []
    x = 2
    out = do_inner_thing(x, out)
    print(out)

do_outer_thing()

CodePudding user response:

I'm not too sure if this is what you meant or not but you're able to place 'out' outside of the function and make do_inner_thing(y) print the string of out.

out = []
def do_inner_thing(y):
    y = y   1
    out.append(y)
    
def do_outer_thing():
    x = 2
    do_inner_thing(x)
    print(str(out)[1])

do_outer_thing()
  • Related