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.

1

3 Answers 3

6
def changeAge(newAge):
    import bar
    bar.age = newAge
Sign up to request clarification or add additional context in comments.

2 Comments

It works perfectly but what is the down side or the drawbacks of importing a full file?
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
-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)

Comments

-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.

2 Comments

As I said, I don't want to return values.
My bad, I haven't read carefully. In this case try bar.age instead the plain age, should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.