0

Possible Duplicate:
Python - how does passing values work?

If I have a variable and instantiate it to None, how can I go about making an assignment that reflects the change in more than one scope?

For example:

def doStuff(test):
    test = "hello world"

def main():
    test = None
    doStuff(test)
    print(test)

If I guessed correctly, then the output is nothing because "test" was passed by value? Is there a way I can make it passed by reference without statically declaring the type before the function?

Community
  • 1
  • 1
Ci3
  • 4,632
  • 10
  • 34
  • 44

4 Answers4

2

When you do this:

def main():
    test = None
    doStuff(test)
    print(test)

You essentialy print the string object (referenced by the test reference) that is in the main()'s scope. To print the inner string object, referenced by the test variable in the doStuff, you should do either of the three:

  • you should either use a print statement inside doStuff

  • or use the global keyword

  • return a value from doStuff that you store in main()'s test.

For that last part, you could find more information here.

Community
  • 1
  • 1
NlightNFotis
  • 9,559
  • 5
  • 43
  • 66
0

You could look into the global keyword.

def doStuff():
    global test
    test = 'Hello World'

The global keyword allows you to assign directly to global variables.

Volatility
  • 31,232
  • 10
  • 80
  • 89
0

If you want doStuff to change the value of test in the main() scope, you should return it, like so:

def doStuff(test):
    test = "hello world"
    return test

def main():
    test = None
    test = doStuff(test)
    print(test)

Of course, in this example, there's no reason to pass test as an input to doStuff(), so you could just do this:

def doStuff():
    test = "hello world" # These 2 lines could be one
    return test          # return "hello world"

def main():
    test = doStuff()
    print(test)
jgritty
  • 11,660
  • 3
  • 38
  • 60
0

You can't directly change the value of local variables from another function - as the others answered you could declare it to be global, or return the new value and assign it. But another way to achieve this that has not yet been mentioned would be using a wrapper class that holds the value in an attribute. Then you can pass the wrapper instance around and modify the attribute:

class Wrapper():
    """a simple wrapper class that holds a single value which defaults to None"""
    def __init__(self, value=None):
        self.value = value

def main():
    test = Wrapper()
    doSomething(test)
    print(test.value)

def doSomething(x):
    x.value = "something"
l4mpi
  • 5,103
  • 3
  • 34
  • 54