John Smith
John Smith

Reputation: 787

How to change variable value in other module?

I have the following modules:

test.py

import test1


var1 = 'Test1'
var2 = 'Test2'

print var1
print var2

test1.modify_vars(var1, var2)

print var1
print var2

and the module

test1.py

def modify_vars(var1, var2):
    var1 += '_changed'
    var2 += '_changed'

I am expecting to get the following output:

Test1
Test2
Test1_changed
Test2_changed

I will get:

Test1
Test2
Test1 
Test2

It is mandatory to avoid importing test module in test1 module.

How to achieve this without returning values from the method ? (sort of reference passing)

Upvotes: 0

Views: 64

Answers (2)

Glostas
Glostas

Reputation: 1180

Your function misses a return value

var1 = 'Test1'
var2 = 'Test2'

def modify_var(var1, var2):
    var1 += '_changed'
    var2 += '_changed'
    return (var1,var2)


(var1,var2) = modify_var(var1,var2)
print var1,var2

Does work.

I believe this requires minimal change to your code.

Tested with python 2.7

Upvotes: -1

Daniel Roseman
Daniel Roseman

Reputation: 599450

Strings are immutable. You cannot do what you want. Using += with a string will always return a new string, which will have nothing to do with whatever var1 and var2 are assigned to.

The only way to achieve something close to what you want (and, to be honest, you should probably change your requirements) is to use a list rather than separate variables, and modify its contents:

var = ['Test1', 'Test2']
...

def modify_var(var):
    var[0] += '_changed'
    var[1] += '_changed'

Upvotes: 3

Related Questions