2

From a file foo.py, I want to change the value of a variable which's placed in a different file, let's say bar.py.

I've tried to do it importing the variable, but it seems that it's imported not as reference.

Just examples:

bar.py:

age = 18

foo.py:

from bar import age

def changeAge(age, newAge):
    age = newAge

changeAge(age, 19)

I've also tried to pass age as parameter from bar.py, but same result, it's not passed by reference so its value is not changed.

bar.py:

from foo import changeAge

age = 18

changeAge(age, 19)

As I said, it didn't work at all. I know I can reach this returning the var from the function, but it will probable make me to change a lot of code and, why not, I want to know if there is a way to do what I need, I'm still a beginner in Python. Another way is to wrapper the variable in an object, a list or something like that, but it doesn't seem too elegant.

Drumnbass
  • 867
  • 1
  • 14
  • 35

3 Answers3

6
def changeAge(newAge):
    import bar
    bar.age = newAge
fferri
  • 18,285
  • 5
  • 46
  • 95
  • It works perfectly but what is the down side or the drawbacks of importing a full file? – Drumnbass Jun 16 '15 at 12:27
  • in terms of performance, it requires parsing that file (and any other modules imported in that file). in terms of symbol table, it creates only a `bar` symbol, and it does so in the scope of the `changeAge` function, so it will not affect the global symbol table – fferri Jun 16 '15 at 12:31
-1

If you just want to change the value of 'age' you can do the following

bar.py

age = 18

foo.py

import bar

def changeAge(newAge):
    bar.age = newAge

changeAge(19)
Denis
  • 530
  • 2
  • 7
-3

You forgot to return newAge.

from bar import age

def changeAge(age, newAge):
    age = newAge
    return newAge

print changeAge(age, 19)

Prints out 19 as expected.

alec_djinn
  • 10,104
  • 8
  • 46
  • 71